Skip to content

Instantly share code, notes, and snippets.

@bhrgunatha
Created December 14, 2022 14:41
Show Gist options
  • Save bhrgunatha/a54c121cef7ae2900d462fefb2726c0c to your computer and use it in GitHub Desktop.
Save bhrgunatha/a54c121cef7ae2900d462fefb2726c0c to your computer and use it in GitHub Desktop.
AoC 2022 Day 14 MUTATIS MALEDICTIS
(define START '(500 0))
(define (part-01 input)
(define cave (make-hash))
(define deepest (scan-cave! cave input))
(count sand?
(hash-values
(drop-sand! cave (first START) (second START) deepest 'void))))
(define (sand? v) (eq? v 'sand))
(define (drop-sand! cave x y deepest floor?)
(define below (add1 y))
(cond [(drops-forever? floor? y deepest) cave]
[(bedrock? floor? y deepest)
(hash-set! cave (list x y) 'sand)
(drop-sand! cave (first START) (second START) deepest floor?)]
[(descend? cave x below deepest) (drop-sand! cave x below deepest floor?)]
[(descend? cave (sub1 x) below deepest) (drop-sand! cave (sub1 x) below deepest floor?)]
[(descend? cave (add1 x) below deepest) (drop-sand! cave (add1 x) below deepest floor?)]
[(feed-blocked? floor? x y)
(hash-set! cave START 'sand)
cave]
[else
(hash-set! cave (list x y) 'sand)
(drop-sand! cave (first START) (second START) deepest floor?)]))
(define (drops-forever? floor? y deepest)
(and (eq? floor? 'void) (= y deepest)))
(define (bedrock? floor? y deepest)
(and (eq? floor? 'floor) (= y deepest)))
(define (feed-blocked? floor? x y)
(and (eq? floor? 'floor) (equal? (list x y) START)))
(define (descend? cave x y deepest)
(and (<= y deepest)
(not (hash-has-key? cave (list x y)))))
(define (scan-cave! cave input)
(for/fold ([deepest 0])
([line (in-list input)])
(max deepest (find-rocks! cave (integers line) deepest))))
(define (find-rocks! cave rocks deepest)
(match rocks
[(list* x/from y/from x/to y/to _)
(find-rocks! cave (drop rocks 2) (add-rocks! cave x/from y/from x/to y/to deepest))]
[_ deepest]))
(define (add-rocks! cave x/from y/from x/to y/to deepest)
(if (= y/from y/to)
(for ([k (in-inclusive-range (min x/from x/to) (max x/from x/to))])
(set! deepest (max deepest y/to))
(hash-set! cave (list k y/from) 'rock))
(for ([k (in-inclusive-range (min y/from y/to) (max y/from y/to))])
(set! deepest (max deepest k))
(hash-set! cave (list x/from k) 'rock)))
deepest)
(define (part-02 input)
(define rock (make-hash))
(define deepest (scan-cave! rock input))
(count sand?
(hash-values
(drop-sand! rock (first START) (second START) (add1 deepest) 'floor))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment