Skip to content

Instantly share code, notes, and snippets.

@nara-l
Forked from scwood/largestRemainderRound.js
Created May 22, 2020 14:51
Show Gist options
  • Save nara-l/b335ffc4ff00b37523a2087a5543a5fa to your computer and use it in GitHub Desktop.
Save nara-l/b335ffc4ff00b37523a2087a5543a5fa to your computer and use it in GitHub Desktop.
Largest remainder round
/**
* largestRemainderRound will round each number in an array to the nearest
* integer but make sure that the the sum of all the numbers still equals
* desiredTotal. Uses Largest Remainder Method. Returns numbers in order they
* came.
*
* @param {number[]} numbers - numbers to round
* @param {number} desiredTotal - total that sum of the return list must equal
* @return {number[]} the list of rounded numbers
* @example
*
* var numbers = [13.6263, 47.9896, 9.59600 28.7880]
* largestRemainderRound(numbers, 100)
*
* // => [14, 48, 9, 29]
*
*/
function largestRemainderRound(numbers, desiredTotal) {
var result = numbers.map(function(number, index) {
return {
floor: Math.floor(number),
remainder: getRemainder(number),
index: index,
};
}).sort(function(a, b) {
return b.remainder - a.remainder;
});
var lowerSum = result.reduce(function(sum, current) {
return sum + current.floor;
}, 0);
var delta = desiredTotal - lowerSum;
for (var i = 0; i < delta; i++) {
result[i].floor++;
}
return result.sort(function(a, b) {
return a.index - b.index;
}).map(function(result) {
return result.floor;
});
}
function getRemainder(number) {
var remainder = number - Math.floor(number);
return remainder.toFixed(4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment