Skip to content

Instantly share code, notes, and snippets.

@kidpollo
Created May 8, 2015 17:03
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 kidpollo/262e9f6481a329be8683 to your computer and use it in GitHub Desktop.
Save kidpollo/262e9f6481a329be8683 to your computer and use it in GitHub Desktop.
Monty Hall problem
(defn monty-hall
""
[]
(let [prize-idx (rand-int 3)
doors [false false false]
doors (assoc doors prize-idx true)
random-pick (rand-int 3)
monty-pick (first
(remove nil? (map-indexed
(fn [idx val]
(if (or
val
(= idx random-pick))
nil
idx))
doors)))
other-door (first (clojure.set/difference #{0 1 2} #{monty-pick random-pick}))
strategy (first (shuffle ["stay" "switch"]))]
[strategy
(nth doors (if (= strategy "stay")
random-pick
other-door))]))
(defn run-a-bunch-o-games [x]
(let [games (for [n (range x)]
(monty-hall))
grouped-games (group-by first games)
stay-games (get grouped-games "stay")
switch-games (get grouped-games "switch")
calc-percent-wins (fn [games]
(let [total-games (count games)
won-games (count (filter second games))]
(* 100.0 (/ won-games total-games))))]
(do (println "Percent of total games won" (calc-percent-wins games))
(println "Percent of stay games won" (calc-percent-wins stay-games))
(println "Percent of switch games won" (calc-percent-wins switch-games)))))
(run-a-bunch-o-games 100)
Percent of total games won 51.0
Percent of stay games won 33.33333333333333
Percent of switch games won 69.38775510204081
=> nil
(run-a-bunch-o-games 1000)
Percent of total games won 49.9
Percent of stay games won 31.72690763052209
Percent of switch games won 67.92828685258964
=> nil
(run-a-bunch-o-games 10)
Percent of total games won 30.0
Percent of stay games won 0.0
Percent of switch games won 50.0
=> nil
(run-a-bunch-o-games 100000)
Percent of total games won 49.889
Percent of stay games won 33.13117969656939
Percent of switch games won 66.62136776050201
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment