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