Day 11 (with mutation...).

This commit is contained in:
Jonathan Chan 2021-12-10 22:21:12 -08:00
parent 52d1e1756d
commit adf8ba4600
3 changed files with 88 additions and 1 deletions

10
input/11.txt Normal file
View File

@ -0,0 +1,10 @@
5421451741
3877321568
7583273864
3451717778
2651615156
6377167526
5182852831
4766856676
3437187583
3633371586

11
lib.rkt
View File

@ -190,10 +190,19 @@
[else #f])) [else #f]))
;; snoc : (listof any) -> any -> (listof any) ;; snoc : (listof any) -> any -> (listof any)
;; Append element to the back of the list. ;; Append element to the back of the list
(define (snoc lst v) (define (snoc lst v)
(append lst (list v))) (append lst (list v)))
;; range* : number? -> (listof number?)
;; range* : number? -> number? -> [number?] -> (listof number?)
;; Like range, but with an inclusive right end
(define-syntax range*
(syntax-rules ()
[(_ n) (range (add1 n))]
[(_ from to) (range from (add1 to))]
[(_ from to step) (range from (add1 to) step)]))
;; scanl : (a -> a -> a) -> (listof a) -> (listof a) ;; scanl : (a -> a -> a) -> (listof a) -> (listof a)
;; foldl that accumulates partial results in a list ;; foldl that accumulates partial results in a list
(define (scanl f init lst) (define (scanl f init lst)

68
src/11.rkt Normal file
View File

@ -0,0 +1,68 @@
#lang curly-fn racket
(require "../lib.rkt")
(define input
(for/vector ([row (problem-input 11)])
(for/vector ([col (string->list row)])
(char->number col))))
(define rows (vector-length input))
(define cols (vector-length (vector-ref input 0)))
(define total (* rows cols))
(define (grid-ref grid row col)
(vector-ref (vector-ref grid row) col))
(define (grid-update! grid row col f)
(vector-set! (vector-ref grid row) col (f (grid-ref grid row col))))
(define (adjs grid row col)
(for*/list ([r (range* (max 0 (sub1 row)) (min (sub1 rows) (add1 row)))]
[c (range* (max 0 (sub1 col)) (min (sub1 cols) (add1 col)))])
(cons r c)))
(define (incr! octopodes)
(for ([row (range rows)])
(for ([col (range cols)])
(grid-update! octopodes row col add1))))
(define (flash! flashed octopodes)
(for*/fold ([newly-flashed '()])
([row (range rows)]
[col (range cols)])
(if (and (not (member (cons row col) flashed))
(> (grid-ref octopodes row col) 9)
(for ([adj (adjs octopodes row col)])
(grid-update! octopodes (car adj) (cdr adj) add1)))
(cons (cons row col) newly-flashed)
newly-flashed)))
(define (decharge! octopodes)
(for ([row (range rows)])
(for ([col (range cols)])
(when (> (grid-ref octopodes row col) 9)
(grid-update! octopodes row col (const 0))))))
(define (step! octopodes)
(incr! octopodes)
(define flashes
(let loop ([flashed '()])
(let ([newly-flashed (flash! flashed octopodes)])
(if (empty? newly-flashed)
(length flashed)
(loop (append newly-flashed flashed))))))
(decharge! octopodes)
flashes)
(define part1
(for/sum ([_ (range 100)])
(step! input)))
(define part2
(let loop ([steps 101])
(if (= (step! input) total)
steps
(loop (add1 steps)))))
(show-solution part1 part2)