summaryrefslogtreecommitdiff
path: root/8-2.scm
diff options
context:
space:
mode:
authorlamp2023-12-11 13:34:24 +0000
committerlamp2023-12-11 13:34:24 +0000
commitd0842f0de1c0a3370ba3fe49918f664863bac100 (patch)
tree446b1c126185600db79753c90a4a592679d1c122 /8-2.scm
parent8b200eebe9c88f98e7136b206790d6ef472a28ac (diff)
add day 8 solutions
Diffstat (limited to '8-2.scm')
-rwxr-xr-x8-2.scm40
1 files changed, 40 insertions, 0 deletions
diff --git a/8-2.scm b/8-2.scm
new file mode 100755
index 0000000..7e68044
--- /dev/null
+++ b/8-2.scm
@@ -0,0 +1,40 @@
+#!/usr/bin/env -S guile -s
+!#
+(use-modules (ice-9 regex)
+ (ice-9 textual-ports)
+ (srfi srfi-1)
+ (srfi srfi-69))
+
+(define (read-lines port)
+ (letrec ((loop (lambda (l ls)
+ (if (eof-object? l)
+ ls
+ (loop (get-line port) (cons l ls))))))
+ (reverse (loop (get-line port) '()))))
+
+(define (parse-line line)
+ (let ((m (string-match "([A-Z]{3}) = \\(([A-Z]{3}), ([A-Z]{3})\\)" line)))
+ `(,(match:substring m 1) (,(match:substring m 2) ,(match:substring m 3)))))
+
+(define (find-node tag tree)
+ (car (filter (lambda (x) (equal? tag (car x))) tree)))
+
+(define (solve-path start tree instructions)
+ (let ((current-instruction 0)
+ (current-node start)
+ (count 0))
+ (while (not (equal? (string-ref current-node 2) #\Z))
+ (if (equal? (string-ref instructions current-instruction) #\L)
+ (set! current-node (caadr (find-node current-node tree)))
+ (set! current-node (cadadr (find-node current-node tree))))
+ (set! current-instruction (modulo (1+ current-instruction) (string-length instructions)))
+ (set! count (1+ count)))
+ count))
+
+(let* ((port (open-input-file "8.txt"))
+ (lines (read-lines port))
+ (instructions (car lines))
+ (tree (map parse-line (cddr lines)))
+ (start-nodes (filter (lambda (x) (equal? (string-ref x 2) #\A)) (map car tree))))
+ (close-port port)
+ (display (apply lcm (map (lambda (x) (solve-path x tree instructions)) start-nodes))))