Last active
August 29, 2015 13:56
-
-
Save shiwano/8806538 to your computer and use it in GitHub Desktop.
weighted random choice
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
module.exports = class WeightedRandomChoice | |
constructor: (args) -> | |
@_weightPairs = _.sortBy _.pairs(args), (pair) -> pair[1] | |
@sum = _.reduce @_weightPairs, ((memo, pair) -> memo + pair[1]), 0 | |
check: (num, weight) -> num - weight <= 0 | |
random: -> _.random 1, @sum | |
select: -> | |
num = @random() | |
for [key, weight] in @_weightPairs | |
return key if @check num, weight | |
num -= weight | |
throw new Error('Invalid choice!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment