Skip to content

Instantly share code, notes, and snippets.

@mkremins
Created October 8, 2014 20:04
Show Gist options
  • Save mkremins/268355a2d45bbd76e0d8 to your computer and use it in GitHub Desktop.
Save mkremins/268355a2d45bbd76e0d8 to your computer and use it in GitHub Desktop.
Weighted random choice
(defn weighted-choice
"Given a map `choices {outcome weight}`, returns a randomly chosen `outcome`.
The likelihood that a particular `outcome` will be chosen is proportional to
its assigned `weight`."
[choices]
(->> choices
(mapcat (fn [[outcome weight]] (repeat weight outcome)))
rand-nth))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment