Skip to content

Instantly share code, notes, and snippets.

@gilesbowkett
Created May 7, 2014 20:00
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 gilesbowkett/daeefcb6e6bbae18bc5e to your computer and use it in GitHub Desktop.
Save gilesbowkett/daeefcb6e6bbae18bc5e to your computer and use it in GitHub Desktop.
clojure problem halp pls
; given this vector
(def probabilities [ 1 0 0 0.5
0 0 1 0 ])
; I want to run (< (rand) probability) against each element
; and ultimately get back either
(def result [ 0 0.75 1.5 ])
; or
(def result [ 0 1.5 ])
; where each row of four, in the above vector, represents row
; index + 0, row + 0.25, row + 0.5, row + 0.75
@gilesbowkett
Copy link
Author

holy shit, I think I got it

(filter (fn [value] (not (nil? value)))
          (map-indexed (fn [idx prob] (cond (< (rand) prob) (* idx 0.25)))
                                    probabilities))

newb

@robknight
Copy link

Beats my effort, I think:

(mapv #(apply + %) (filter #(< (rand) (second %)) (map vector (range 0 (* (count probabilities) 0.25) 0.25) probabilities)))

My result is a vector and not a list, but it's also quite a bit less readable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment