Created
October 8, 2014 20:04
-
-
Save mkremins/268355a2d45bbd76e0d8 to your computer and use it in GitHub Desktop.
Weighted random choice
This file contains hidden or 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
(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