1
0
Fork 0

Day 14: Some cleanup.

This commit is contained in:
Jonathan Chan 2021-12-13 23:05:38 -08:00 committed by Jonathan Chan
parent 80a60ce2f8
commit 08ceca323d
1 changed files with 16 additions and 20 deletions

View File

@ -3,36 +3,32 @@
(require "../lib.rkt")
(define-values (template rules left-end right-end)
(match-let ([(list `(,template*) rules) (problem-input-grouped-lines 14)])
(define template (map char->symbol (string->list template*)))
(match-let* ([`((,template*) ,rules) (problem-input-grouped-lines 14)]
[(and template `(,left-end ,@_ ,right-end)) (string->list template*)])
(values (for/hash ([left template]
[right (rest template)])
(values (cons left right) 1))
(for/hash ([rule rules])
(match-let ([(list _ left right insert) (regexp-match #px"(\\w)(\\w) -> (\\w)" rule)])
(values (cons (string->symbol left)
(string->symbol right))
(string->symbol insert))))
(first template) (last template))))
(match-let ([`(,_ ,left ,right ,insert) (regexp-match #px"(\\w)(\\w) -> (\\w)" rule)])
(values (cons (string-ref left 0)
(string-ref right 0))
(string-ref insert 0))))
left-end right-end)))
(define (step template)
(for/fold ([polymer (hash)])
([pair (hash-keys template)])
(match-let* ([(cons left right) pair]
[insert (hash-ref rules pair)]
[count (hash-ref template pair)]
[polymer (hash-update polymer (cons left insert) #{+ % count} 0)]
[polymer (hash-update polymer (cons insert right) #{+ % count} 0)])
polymer)))
([(k v) template])
(define insert (hash-ref rules k))
(~> polymer
(hash-update (cons (car k) insert) #{+ % v} 0)
(hash-update (cons insert (cdr k)) #{+ % v} 0))))
(define (count n)
(for/fold ([counts (hash right-end 1 left-end 1)]
#:result (let ([counts (hash-values counts)])
(/ (- (maximum counts) (minimum counts)) 2)))
#:result (#{/ (- (maximum %) (minimum %)) 2} (hash-values counts)))
([(k v) ((iterate step n) template)])
(match-let* ([(cons left right) k]
[counts (hash-update counts left #{+ % v} 0)]
[counts (hash-update counts right #{+ % v} 0)])
counts)))
(~> counts
(hash-update (car k) #{+ % v} 0)
(hash-update (cdr k) #{+ % v} 0))))
(show-solution (count 10) (count 40))