Skip to content

Instantly share code, notes, and snippets.

@aesnyder
Last active October 22, 2017 16:55
Show Gist options
  • Save aesnyder/c8898a9002e50ba65373 to your computer and use it in GitHub Desktop.
Save aesnyder/c8898a9002e50ba65373 to your computer and use it in GitHub Desktop.
Weighted random value in underscore or lodash
## First you can generate a weighted array
weighted 1: true, 2: false # [true, false, false]
weighted 1: true, 3: false # [true, false, false, false]
## Then random picks one randomly
## The following will return true or false with a 1:3 ratio
random weighted 1: true, 3: false
# here's the magic, you need underscore or lodash
weighted = (weightMap) ->
_ weightMap
.map (val, weight) -> _.times weight, -> val
.flatten()
.value()
random = (arr) -> _.shuffle(arr)[0]
@paulintrognon
Copy link

You can replace _.shuffle(arr)[0]by _.pick(arr) I believe!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment