Created
October 2, 2018 13:21
-
-
Save tggreene/ec094bb9f5d554abcb999fa857af8cc0 to your computer and use it in GitHub Desktop.
randw-nth #clojure
This file contains 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 randw-nth | |
"As rand-nth but takes weight-fn applied to col to weight selection e.g. | |
(randw-nth [{:type :a :weight 3} | |
{:type :b :weight 1}] | |
:weight) | |
; => {:type :a :weight 3} is chosen 3/4 times" | |
[col weight-fn] | |
(let [weights (reductions + (map weight-fn col)) | |
choices (map vector col weights) | |
r (rand-int (last weights))] | |
(loop [[[k w] & more] choices] | |
(when w | |
(if (< r w) | |
k | |
(recur more)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment