Skip to content

Instantly share code, notes, and snippets.

@deque-blog
Created June 12, 2017 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deque-blog/77048bae2305957fcd6db981ffaf13e8 to your computer and use it in GitHub Desktop.
Save deque-blog/77048bae2305957fcd6db981ffaf13e8 to your computer and use it in GitHub Desktop.
(defn enumerated-distribution-gen
"Create a random generator producing weighted inputs
- Input: a sequence of pairs [value weight-of-value]
- Output: a random generator that picks values from the input
such that P(value) = Weight(value) / Sum(all weights)"
[enum-dist]
{:pre [(pos? (count enum-dist))]}
(if (= 1 (count enum-dist))
(constantly (ffirst enum-dist))
(let [buckets (enum-dist->buckets enum-dist)]
(fn []
(let [[v1 v2 p] (rand-nth buckets)]
(if (< (rand) p) v1 v2))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment