Last active
February 14, 2023 15:14
-
-
Save hijonathan/e597addcc327c9bd017c to your computer and use it in GitHub Desktop.
Javascript implementation of the largest remainder method http://en.wikipedia.org/wiki/Largest_remainder_method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
values = [ | |
13.626332 | |
47.989636 | |
9.596008 | |
28.788024 | |
] | |
# Round these percentage values into integers, ensuring that they equal 100% at the end. | |
roundedValues = getLargestRemainder values, 100 | |
# [14, 48, 9, 29] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Uses underscore.js, for brevity. | |
getLargestRemainder = (values, desiredSum) -> | |
sum = 0 | |
parts = _.map values, (item, i) -> | |
# Get rounded down integer values. | |
int = item | 0 | |
sum += int | |
return { | |
integer: int | |
decimal: item % 1 | |
# Used to return values in original order. | |
originalIndex: i | |
} | |
if sum isnt desiredSum | |
# Sort in descending order. | |
parts = _(parts).sortBy('decimal').reverse() | |
diff = desiredSum - sum | |
i = 0 | |
# Distribute additions. | |
while i < diff | |
parts[i].integer++ | |
i++ | |
return _.pluck _(parts).sortBy('originalIndex'), 'integer' | |
Hey @djabif, I don't get much of coffee and your implementation really helped. Thanks!!
I just changed:
valueParts = valueParts.sort(x => x.decimal); valueParts.sort(x => x.originalIndex)
to, respectively,
valueParts = valueParts.sort((a, b) => b.decimal - a.decimal); valueParts.sort((a, b) => a.originalIndex - b.originalIndex)
as that is required to correctly sort the list by descending/ascending. Otherwise JS will just sort them alphabetically which can lead to errors.
Hey @djabif, I don't get much of coffee and your implementation really helped. Thanks!!
I just changed:
valueParts = valueParts.sort(x => x.decimal); valueParts.sort(x => x.originalIndex)to, respectively,
valueParts = valueParts.sort((a, b) => b.decimal - a.decimal); valueParts.sort((a, b) => a.originalIndex - b.originalIndex)as that is required to correctly sort the list by descending/ascending. Otherwise JS will just sort them alphabetically which can lead to errors.
Thanks for your fix and for the gist @hijonathan.
FYI the values are different on Chrom/Firefox than in Safari without this fix.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @hijonathan, thanks for this gist!
I translated it to typescript. Will leave the code here just in case anyone needs it.