Skip to content

Instantly share code, notes, and snippets.

@shiwano
Last active August 29, 2015 13:56
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 shiwano/8806538 to your computer and use it in GitHub Desktop.
Save shiwano/8806538 to your computer and use it in GitHub Desktop.
weighted random choice
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