Skip to content

Instantly share code, notes, and snippets.

@aaronjeline
Created December 25, 2020 22:24
Show Gist options
  • Save aaronjeline/34c1a8ed1f2060e2a7bbbf6400f35dfe to your computer and use it in GitHub Desktop.
Save aaronjeline/34c1a8ed1f2060e2a7bbbf6400f35dfe to your computer and use it in GitHub Desktop.
Monty Hall Simulation in Racket
#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