diff options
author | J.J <thechairman@thechairman.info> | 2023-11-30 17:10:00 -0500 |
---|---|---|
committer | J.J <thechairman@thechairman.info> | 2023-11-30 17:10:00 -0500 |
commit | 8ab65dc2da1742eb86ec636c50c7018385b68167 (patch) | |
tree | c4fd556aca9b867cfa1f2f174128c30857353884 /aoc2020/day-11 | |
parent | fafbeaf9e3c09ba7a5bea7e47d5736001f8a5aa1 (diff) | |
download | gleam_aoc-8ab65dc2da1742eb86ec636c50c7018385b68167.tar.gz gleam_aoc-8ab65dc2da1742eb86ec636c50c7018385b68167.zip |
prep for 2023, renaming for consistency
Diffstat (limited to 'aoc2020/day-11')
-rw-r--r-- | aoc2020/day-11/day-11.rkt | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/aoc2020/day-11/day-11.rkt b/aoc2020/day-11/day-11.rkt new file mode 100644 index 0000000..e2fe052 --- /dev/null +++ b/aoc2020/day-11/day-11.rkt @@ -0,0 +1,60 @@ +#lang racket + +(require advent-of-code) + +(define raw-grid (fetch-aoc-input (find-session) 2020 11)) + +(define/match (parse _) + [(#\L) 'empty] + [(#\#) 'occupied] + [(#\.) 'floor]) + +(define seat-grid + (for*/hash ([(row r) (in-indexed (in-list (string-split raw-grid)))] + [(col c) (in-indexed (in-string row))]) + (values (cons r c) (parse col)))) + +(define (next-seat-state seat state h rule [max-occupy 4]) + (define neighbor-states (rule seat h)) + (match* (state (count (curry eq? 'occupied) neighbor-states)) + [('empty 0) 'occupied] + [('occupied n) + #:when (>= n max-occupy) + 'empty] + [(_ _) state])) + +(define (stabilize h [i 1] #:rule rule #:max-occupy [max-occupy 4]) + (define h* + (for/hash ([(seat state) (in-hash h)]) + (cond + [(eq? state 'floor) (values seat state)] + [else (values seat (next-seat-state seat state h rule max-occupy))]))) + (if (equal? h h*) + (count (curry equal? 'occupied) (hash-values h)) + (stabilize h* (add1 i) #:rule rule #:max-occupy max-occupy))) + +;; part 1 +(define (find-nearest-neighbors p h) + (match-define (cons r c) p) + (for*/list ([r* (in-inclusive-range (sub1 r) (add1 r))] + [c* (in-inclusive-range (sub1 c) (add1 c))] + [p* (in-value (cons r* c*))] + #:unless (equal? p p*)) + (hash-ref h p* 'out-of-bounds))) + +(stabilize seat-grid #:rule find-nearest-neighbors) + +;; part 2 +(define (find-visible-neighbors p h) + (match-define (cons r c) p) + (define directions + (for*/list ([dr '(-1 0 1)] [dc '(-1 0 1)] #:unless (= 0 dr dc)) + (cons dr dc))) + (for/list ([dir (in-list directions)] #:do [(match-define (cons dr dc) dir)]) + (for*/first ([i (in-naturals 1)] + #:do [(define p* (cons (+ r (* i dr)) (+ c (* i dc)))) + (define state (hash-ref h p* 'out-of-bounds))] + #:unless (equal? state 'floor)) + state))) + +(stabilize seat-grid #:rule find-visible-neighbors #:max-occupy 5) |