From 9571487669f434cc66e9497810a4f07d1568e0fc Mon Sep 17 00:00:00 2001 From: Jonathan Chan Date: Mon, 13 Dec 2021 23:05:38 -0800 Subject: [PATCH] Day 14: Some cleanup. --- src/14.rkt | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/14.rkt b/src/14.rkt index 55057e4..61ac3c4 100644 --- a/src/14.rkt +++ b/src/14.rkt @@ -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)) \ No newline at end of file