Skip to content

Instantly share code, notes, and snippets.

@tggreene
Created October 2, 2018 13:21
Show Gist options
  • Save tggreene/ec094bb9f5d554abcb999fa857af8cc0 to your computer and use it in GitHub Desktop.
Save tggreene/ec094bb9f5d554abcb999fa857af8cc0 to your computer and use it in GitHub Desktop.
randw-nth #clojure
(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