aoc2023/8.rkt

57 lines
1.6 KiB
Racket
Raw Normal View History

2023-12-08 05:20:58 +00:00
#lang curly-fn racket
(require "scripts/aoc.rkt")
;; 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)
([inst (in-cycle (in-list (first input)))])
#:break (equal? cur "ZZZ")
(define next (follow (second input) cur inst))
(values next (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)))
(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)
(module+ main
(define input (parse "inputs/8"))
(answer 8 1 (time (part1 input)))
(answer 8 2 (time (part2 input)))
(displayln "meow"))