Skip to content

Instantly share code, notes, and snippets.

@kjirou
Created September 13, 2013 02:31
Show Gist options
  • Save kjirou/6546225 to your computer and use it in GitHub Desktop.
Save kjirou/6546225 to your computer and use it in GitHub Desktop.
# Choice randomly according to ratios
#
# e.g.
#
# ratioMap=[[1.0, 'x'], [2.0, 'y'], [3.0, 'z']]
# -> x=1/6, y=2/6, z=3/6
#
# Can also write like this:
# ratioMap={ x:1.0, y:2.0, z:3.0 }
#
@choiceRandomlyByRatio = (ratioMap) ->
if not _.isArray(ratioMap) and _.isObject(ratioMap)
ratioMap = _(ratioMap).map (v, k) -> [v, k]
total = _.reduce(ratioMap, ((memo, v) -> memo + v[0]), 0)
roll = Math.random() * total
summing = 0
for v in ratioMap
summing += v[0]
return v[1] if roll < summing
throw new Error "Impossible case"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment