Skip to content

Instantly share code, notes, and snippets.

@itdxer
Last active August 14, 2018 05:21
Show Gist options
  • Save itdxer/f6a96e62ae4ce8a9f9cd9ec542dac88e to your computer and use it in GitHub Desktop.
Save itdxer/f6a96e62ae4ce8a9f9cd9ec542dac88e to your computer and use it in GitHub Desktop.
(defn replace-values
[array current-value new-value]
(assoc array (.indexOf array current-value) new-value))
(defn swap-balls-in-boxes
[box-a box-b]
(let [random-ball-a (rand-nth box-a)
random-ball-b (rand-nth box-b)]
[(replace-values box-a random-ball-a random-ball-b)
(replace-values box-b random-ball-b random-ball-a)]))
(defn simulation
[]
(let [box-a ["white"]
box-b ["white", "black"]]
(->> [box-a box-b]
(apply swap-balls-in-boxes)
(rand-nth)
(rand-nth))))
(defn avg-of
[n coll]
(float (/ (count coll) n)))
(defn white-ball-probability
[n-simulations]
(->> (repeatedly simulation)
(take n-simulations)
(filter #(= % "white"))
(avg-of n-simulations)))
(white-ball-probability 100000) ; should be 0.625 on average
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment