3 coin flip Monte Carlo simulation in Clojure
Code
;; three_coin_toss_montecarlo.clj
;; Montecarlo simulation of 3 coin toss
(defn toss-thrice []
(repeatedly 3 #(rand-nth ["H" "T"])))
(defn samples [num]
(repeatedly num toss-thrice))
(defn nil-to-zero [x]
(if (nil? x) 0 x))
(defn side-count [coll side]
(nil-to-zero (get (frequencies coll) side)))
(defn heads-count [coll]
(side-count coll "H"))
(defn tails-count [coll]
(side-count coll "T"))
(def data (samples 100))
(count (filter #(= (tails-count %) 2) data))
(count (filter #(= (heads-count %) 2) data))
(count (filter #(= (tails-count %) 3) data))
(count (filter #(= (heads-count %) 3) data))
(count (filter #(= (tails-count %) 0) data))
(count (filter #(= (heads-count %) 0) data))
(apply + (map #(tails-count %) data))
(apply + (map #(heads-count %) data))
Notes