From d0842f0de1c0a3370ba3fe49918f664863bac100 Mon Sep 17 00:00:00 2001 From: lamp Date: Mon, 11 Dec 2023 13:34:24 +0000 Subject: add day 8 solutions --- 8.scm | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100755 8.scm (limited to '8.scm') diff --git a/8.scm b/8.scm new file mode 100755 index 0000000..f4025e8 --- /dev/null +++ b/8.scm @@ -0,0 +1,36 @@ +#!/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))) + +(let* ((port (open-input-file "8.txt")) + (lines (read-lines port)) + (instructions (car lines)) + (tree (map parse-line (cddr lines))) + (current-instruction 0) + (current-node "AAA") + (count 0)) + (close-port port) + (while (not (equal? current-node "ZZZ")) + (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))) + (display count)) -- cgit v1.2.3