Skip to content

Instantly share code, notes, and snippets.

@aaronjeline
Created March 18, 2024 20:37
Show Gist options
  • Save aaronjeline/68ef0a2e60de8a88b39152900a485bcf to your computer and use it in GitHub Desktop.
Save aaronjeline/68ef0a2e60de8a88b39152900a485bcf to your computer and use it in GitHub Desktop.
#lang racket
(define N 1000)
(define (main)
(printf "N: ~a\n" N)
(define data (play-n-games N))
(printf "Alice wins: ~a\n" (count alice? data))
(printf "Bob wins: ~a\n" (count bob? data))
(printf "Ties: ~a\n" (count tie? data)))
(define (play-n-games n)
(build-list n (λ (i) (play-game))))
(define (play-game)
(define flips (flip-n-coins 100))
(wins (score-game flips)))
(define (score-game flips)
; Alice's score is hh
; Bob's score is ht
`((alice ,(score-hh flips))
(bob ,(score-ht flips))))
(define (game-score-alice score)
(match score
[`((alice ,s) (bob ,_)) s]))
(define (game-score-bob score)
(match score
[`((alice ,_) (bob ,s)) s]))
(define (wins s)
(cond
[(= (game-score-alice s) (game-score-bob s))
'tie]
[(> (game-score-alice s) (game-score-bob s))
'alice]
[else 'bob]))
(define (alice? x)
(eq? x 'alice))
(define (bob? x)
(eq? x 'bob))
(define (tie? x)
(eq? x 'tie))
(define (score-hh lst)
(match lst
[(cons 'h (cons 'h rest))
(add1 (score-hh (cons 'h rest)))]
[(cons _ rest)
(score-hh rest)]
['() 0]))
(define (score-ht lst)
(match lst
[(cons 'h (cons 't rest))
(add1 (score-ht (cons 't rest)))]
[(cons other rest)
(score-ht rest)]
['() 0]))
(define (flip-n-coins n)
(build-list n (λ (i) (fair-coin-flip))))
(define (fair-coin-flip)
(match (random 2)
[0 'h]
[1 't]))
(module+ test
(require rackunit)
; Test case from tweet
(check-equal?
(score-game '(t h h h t))
`((alice 2) (bob 1))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment