Skip to content

Instantly share code, notes, and snippets.

@filippomangione
Created November 3, 2014 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filippomangione/0695c8825190954ce0f2 to your computer and use it in GitHub Desktop.
Save filippomangione/0695c8825190954ce0f2 to your computer and use it in GitHub Desktop.
Add Up to 100%
var _ = require('./underscore.js');
function foo(l, target) {
var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0);
return _.chain(l).
sortBy(function(x) { return Math.round(x) - x }).
map(function(x, i) { return Math.round(x) + (off > i) - (i >= (l.length + off)) }).
value();
}
foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // => [48, 29, 14, 9]
foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // => [17, 17, 17, 17, 16, 16]
foo([33.333, 33.333, 33.333], 100) // => [34, 33, 33]
foo([33.3, 33.3, 33.3, 0.1], 100) // => [34, 33, 33, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment