Created
March 17, 2015 14:51
-
-
Save ddillinger/db1b30d2b963bb204442 to your computer and use it in GitHub Desktop.
monty hall simulator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns monty.core) | |
;; game setup and rules | |
(defn gen-doors | |
"Generates a shuffled triple vector of two :goat and one :car entry." | |
[] | |
(shuffle [:goat :goat :car])) | |
(defn choose | |
"Randomly chooses an index into the doors and returns it." | |
[doors] | |
(rand-nth (range (count doors)))) | |
(defn monty-knows | |
"Given the doors and a guessed index, returns the index of one of the other | |
entries, which is guaranteed to be a losing choice." | |
[doors n] | |
(let [not-chosen (remove #(= n %) (range 3))] | |
(if (= :car (get doors n)) | |
(rand-nth not-chosen) | |
(rand-nth (remove #(= :car (get doors %)) not-chosen))))) | |
(defn win? | |
"Did you win?" | |
[doors n] | |
(= :car (get doors n))) | |
;; strategies | |
(defn stand-pat | |
"Chooses to stay with the originally guessed number. Returns the index." | |
[choice monty] | |
choice) | |
(defn change-choice | |
"Chooses to switch to the other choice monty didn't eliminate. Returns the | |
index number." | |
[choice monty] | |
(first (remove #(or (= % choice) (= % monty)) (range 3)))) | |
;; simulation | |
(defn play | |
"Given a strategy, generates a doors triple, randomly chooses one, asks monty | |
to rule another out, and then applies the given strategy to select a final | |
choice index. Returns boolean of whether the strategy chose a winning index." | |
[f] | |
(let [doors (gen-doors) | |
choice (choose doors) | |
monty (monty-knows doors choice) | |
choice2 (f choice monty)] | |
(win? doors choice2))) | |
(defn sims | |
"Given a strategy and a number of games to play, plays the game n times | |
applying the given strategy." | |
[f n] | |
(let [runs (for [i (range n)] | |
(play f))] | |
(/ (count (remove false? runs)) (float n)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment