diff options
Diffstat (limited to '2024/day01/main.scm')
-rwxr-xr-x | 2024/day01/main.scm | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/2024/day01/main.scm b/2024/day01/main.scm new file mode 100755 index 0000000..9334264 --- /dev/null +++ b/2024/day01/main.scm @@ -0,0 +1,68 @@ +#!/usr/bin/guile -s +!# + +(add-to-load-path (format #f "~a/2024" (getcwd))) +(add-to-load-path (format #f "~a/.." (dirname (current-filename)))) + +(use-modules + (aoc-utils) + (srfi srfi-1) + (srfi srfi-9) + (ice-9 regex)) + +(define line-rx "([0-9]+)\\s+([0-9]+)") + +(define (match-line line) + (let ((match (string-match line-rx line))) + (list (string->number (match:substring match 1)) + (string->number (match:substring match 2))))) + +(define (first-sorted-list l) + (sort (map (lambda (pair) (car pair)) l) <)) +(define (second-sorted-list l) + (sort (map (lambda (pair) (car (cdr pair))) l) <)) + +(define (part1 lines) + (let* ((lines (map (lambda (line) (match-line line)) + lines)) + (first-list (first-sorted-list lines)) + (second-list (second-sorted-list lines))) + (fold (lambda (pair acc) + (+ acc (abs (- (first pair) (second pair))))) + 0 + (zip first-list second-list)))) + +(define (make-counter l) + (let ((h (make-hash-table))) + (for-each (lambda (n) + (if (hash-ref h n) + (hash-set! h n (1+ (hash-ref h n))) + (hash-set! h n 1))) + l) + h)) + +(define (part2 lines) + (let* ((lines (map (lambda (line) (match-line line)) lines)) + (first-list (map (lambda (pair) (car pair)) lines)) + (second-list (map (lambda (pair) (car (cdr pair))) lines)) + (counter-map (make-counter second-list))) + (fold (lambda (n acc) + ;; (display n) (display "-") (display acc) (newline) + (+ (* n (if (hash-ref counter-map n) + (hash-ref counter-map n) + 0)) + acc)) + 0 + first-list))) + + +(define (main) + (let ((lines (file->list "input.txt"))) + (display "Part1: ") + (display (part1 lines)) + (newline) + (display "Part2: ") + (display (part2 lines)) + (newline))) + +(main) |