summaryrefslogtreecommitdiff
path: root/5.scm
diff options
context:
space:
mode:
authorlamp2023-12-05 13:27:03 +0000
committerlamp2023-12-05 13:27:03 +0000
commitd68ad4401a8685e51dac64caede973efc56c9189 (patch)
tree64bd4b152e91fccf04258d1d28c98718d32e37fc /5.scm
parent843d10f9a8ff2f1d9b22acae18f0ee2ae0c8d9fd (diff)
add day 5 part 1 solution
Diffstat (limited to '5.scm')
-rwxr-xr-x5.scm54
1 files changed, 54 insertions, 0 deletions
diff --git a/5.scm b/5.scm
new file mode 100755
index 0000000..39929d3
--- /dev/null
+++ b/5.scm
@@ -0,0 +1,54 @@
+#!/usr/bin/env -S guile -s
+!#
+(use-modules (ice-9 regex)
+ (ice-9 textual-ports)
+ (srfi srfi-1))
+
+(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 (split-up nums)
+ (map string->number (filter (lambda (x) (not (string-null? x))) (string-split nums char-set:whitespace))))
+
+(define (perform-mapping val map)
+ (let* ((mapping (filter (lambda (x) (and (> val (cadr x))
+ (< val (+ (cadr x) (caddr x))))) map)))
+ (if (null? mapping) val
+ (+ val (- (caar mapping) (cadar mapping))))))
+
+(define (perform-all-mappings val maps)
+ (do ((i 0 (1+ i))) ((= i (length maps)))
+ (set! val (perform-mapping val (list-ref maps i))))
+ val)
+
+(define (parse-next-map lines)
+ (let ((map-started #f)
+ (map-parsed #f)
+ (current-map '()))
+ (while (not map-parsed)
+ (if (and (not map-started)
+ (string-match "map" (car lines)))
+ (set! map-started #t)
+ (when map-started
+ (if (string-match "[0-9]" (car lines))
+ (set! current-map (append current-map `(,(split-up (car lines)))))
+ (set! map-parsed #t))))
+ (set! lines (cdr lines)))
+ `(,current-map ,lines)))
+
+(let* ((port (open-input-file "5.txt"))
+ (lines (read-lines port))
+ (seeds (split-up (match:substring (string-match ": ([0-9| ]+)" (car lines)) 1)))
+ (lines (cdr lines))
+ (maps '()))
+ (close-port port)
+ (do ((i 0 (1+ i))) ((= i 7))
+ (let ((res (parse-next-map lines)))
+ (set! maps (append maps `(,(car res))))
+ (set! lines (cadr res))))
+ (let ((locations (map (lambda (x) (perform-all-mappings x maps)) seeds)))
+ (display (fold (lambda (x y) (if (> x y) y x)) (car locations) locations))))