diff options
author | Matias Linares <matias@deprecated.org> | 2024-12-01 21:54:12 -0300 |
---|---|---|
committer | Matias Linares <matias@deprecated.org> | 2024-12-01 21:54:12 -0300 |
commit | f9f11695270872f7cf8c6616274bb2ef340575ec (patch) | |
tree | 570f8f97dfa8d463d3da9289c7cd7ddcafb6580e /2024/day01/main.scm | |
parent | a73cbbc18cb365cfcb069cb712f55dc30325c974 (diff) | |
download | advent-of-code-f9f11695270872f7cf8c6616274bb2ef340575ec.tar.gz |
Add 2024
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) |