diff options
author | lamp | 2023-12-05 17:24:38 +0000 |
---|---|---|
committer | lamp | 2023-12-05 17:24:38 +0000 |
commit | 92d487dc052788b0ef77071cccad2427c20f66df (patch) | |
tree | 65ee2ca4ddb9962e310622bff194853e4e8f4097 /5-2.scm | |
parent | d68ad4401a8685e51dac64caede973efc56c9189 (diff) |
add initial day 5 part 2 solution
Diffstat (limited to '5-2.scm')
-rwxr-xr-x | 5-2.scm | 62 |
1 files changed, 62 insertions, 0 deletions
@@ -0,0 +1,62 @@ +#!/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 '()) + (current #nil)) + (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)))) + (set! current (perform-all-mappings (car seeds) maps)) + (while (not (null? seeds)) + (display "Starting Iteration...\n") + (do ((j 0 (1+ j))) ((= j (cadr seeds))) + (let ((val (perform-all-mappings (+ (car seeds) j) maps))) + (when (> current val) + (set! current val)))) + (set! seeds (cddr seeds))) + (display current)) |