Skip to content

Instantly share code, notes, and snippets.

@shriphani
Created November 12, 2012 18:42
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 shriphani/4061097 to your computer and use it in GitHub Desktop.
Save shriphani/4061097 to your computer and use it in GitHub Desktop.
random-choice implementation using user-supplied probabilities for list items
(define (random-choice-probs ns n-probs)
(let ((x (random))
(cum-prob 0.0)
(res (first ns)))
(define (inner)
(for ((item ns)
(item-prob n-probs))
(begin
(set! cum-prob (+ cum-prob item-prob))
(when (< x cum-prob)
(begin
(set! res item)
(set! x +inf.0)))))
res)
(inner)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment