Created
December 25, 2020 22:24
-
-
Save aaronjeline/34c1a8ed1f2060e2a7bbbf6400f35dfe to your computer and use it in GitHub Desktop.
Monty Hall Simulation in Racket
This file contains hidden or 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
#lang racket | |
(define (simulate strategy) | |
(define car (random 3)) | |
(define goats (list (modulo (add1 car) 3) | |
(modulo (sub1 car) 3))) | |
(define guess (random 3)) | |
(define reveal (list-ref goats (random 2))) | |
(define final (strategy guess reveal)) | |
(if (= final car) 'win 'lose)) | |
(define (const guess r) guess) | |
(define (flip guess r) | |
(car (filter | |
(λ (x) (not (or (= x guess) (= x r)))) | |
(range 3)))) | |
(define (game rounds strategy) | |
(define won 0) | |
(for [(i (range rounds))] | |
(if (eq? (simulate strategy) 'win) | |
(set! won (add1 won)) | |
(void))) | |
(exact->inexact (/ won rounds))) | |
(define rounds 1000000) | |
(define const-results (game rounds const)) | |
(define flip-results (game rounds flip)) | |
;; Print results | |
;; | |
(displayln (format "Win percent for staying with same door: ~a%" | |
const-results)) | |
(displayln (format "Win percent for always flipping door: ~a%" | |
flip-results)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment