From f9f11695270872f7cf8c6616274bb2ef340575ec Mon Sep 17 00:00:00 2001 From: Matias Linares Date: Sun, 1 Dec 2024 21:54:12 -0300 Subject: Add 2024 --- .gitignore | 3 ++- 2024/aoc-utils.scm | 11 +++++++++ 2024/day01/main.scm | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 2024/aoc-utils.scm create mode 100755 2024/day01/main.scm diff --git a/.gitignore b/.gitignore index 8f39b4e..123fb15 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .precomp -target/ \ No newline at end of file +target/ +*.txt \ No newline at end of file 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) -- cgit v1.2.3-70-g09d2