diff --git a/8.rkt b/8.rkt index 1d8d2aa..b86754e 100644 --- a/8.rkt +++ b/8.rkt @@ -4,50 +4,30 @@ ;; solution for day 8 -(define (follow mapl cur inst) - (define node - (for/first ([entry (in-list mapl)] - #:when (equal? (first entry) cur)) - entry)) - (match inst - [#\L (second node)] - [#\R (third node)])) - -(define (part1 input) - (for/fold ([cur "AAA"] [cnt 0] #:result cnt) +(define (part1 input [cur "AAA"] [break? #{equal? % "ZZZ"}]) + (for/fold ([cur cur] [cnt 0] #:result cnt) ([inst (in-cycle (in-list (first input)))]) - #:break (equal? cur "ZZZ") - (define next (follow (second input) cur inst)) - (values next (add1 cnt)))) + #:break (break? cur) + (values (inst (hash-ref (second input) cur)) + (add1 cnt)))) (define (part2 input) - (define all-as - (for/list ([x (in-list (second input))] #:when (regexp-match? #px"^..A$" (first x))) - (first x))) - (define (end-z? c) - (regexp-match? #px"^..Z$" c)) - - (define (run-item item) - (for/fold ([cur item] [cnt 0] #:result cnt) - ([inst (in-cycle (in-list (first input)))]) - #:break (end-z? cur) - (define next (follow (second input) cur inst)) - (values next (add1 cnt)))) - - (apply lcm (map run-item all-as))) - + (~> (filter #{string-suffix? % "A"} + (hash-keys (second input))) + (map #{part1 input % #{string-suffix? % "Z"}} _) + (apply lcm _))) (define (parse fname) - (match-define (list instl mapl) (string-split (file->string fname) "\n\n")) - (list (string->list instl) - (for/list ([line (in-list (string-split mapl "\n"))]) - (match-define (pregexp #px"([A-Z0-9]{3}) = .([A-Z0-9]{3}), ([A-Z0-9]{3})." - (list _ node left right)) - line) - (list node left right)))) - -; (part2 (parse "inputs/8-test1")) -; (error) + (match-define (list* instl _ mapl) (file->lines fname)) + (list + (for/list ([c (in-string instl)]) + (match c + [#\L first] + [#\R second])) + (for/hash ([line (in-list mapl)]) + (match-define (list node left right) + (regexp-match* #px"[A-Z0-9]{3}" line)) + (values node (list left right))))) (module+ main (define input (parse "inputs/8"))