diff options
Diffstat (limited to '2024')
-rw-r--r-- | 2024/aoc-utils.scm | 11 | ||||
-rwxr-xr-x | 2024/day01/main.scm | 68 |
2 files changed, 79 insertions, 0 deletions
diff --git a/2024/aoc-utils.scm b/2024/aoc-utils.scm new file mode 100644 index 0000000..6b57aa5 --- /dev/null +++ b/2024/aoc-utils.scm @@ -0,0 +1,11 @@ +(define-module (aoc-utils) + #:use-module (srfi srfi-1) + #:use-module (srfi srfi-9) + #:use-module (ice-9 regex) + #:use-module (ice-9 rdelim) + #:export (file->list)) + +(define (file->list filename) + (let ((lines (string-split (call-with-input-file filename read-string) #\Newline))) + ; Remove EOF token + (take lines (1- (length lines))))) 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) |