aboutsummaryrefslogtreecommitdiff
path: root/day11.scm
diff options
context:
space:
mode:
authorJuan Marín Noguera <juan@mnpi.eu>2024-12-15 11:59:53 +0100
committerJuan Marín Noguera <juan@mnpi.eu>2024-12-15 12:01:06 +0100
commit2e904e83f6fbc001e5b265d94283841a51050fac (patch)
tree474b533a0d76e8c0d67a3d2d2560abfac721f84f /day11.scm
parent774d3ff46a854bd9a9379ef2c0945048ec5aee1e (diff)
Days 08--12
These days have been done while traveling, so they may be less modular due to time/phone-screen constraints.
Diffstat (limited to 'day11.scm')
-rw-r--r--day11.scm72
1 files changed, 72 insertions, 0 deletions
diff --git a/day11.scm b/day11.scm
new file mode 100644
index 0000000..76ca159
--- /dev/null
+++ b/day11.scm
@@ -0,0 +1,72 @@
+(define-module (day11)
+ #:use-module (ice-9 rdelim))
+
+(define (part1 port)
+ (define line (read-line port))
+ (define nums (map string->number (string-split line #\space)))
+ (define (blink lst acc)
+ (if (null? lst)
+ (reverse acc)
+ (blink (cdr lst)
+ (if (zero? (car lst))
+ (cons 1 acc)
+ (let ((s (number->string (car lst))))
+ (if (even? (string-length s))
+ (cons (string->number (substring s (/ (string-length s) 2)))
+ (cons (string->number (substring s 0 (/ (string-length s) 2)))
+ acc))
+ (cons (* (car lst) 2024) acc)))))))
+ (define (iter lst left)
+ (if (zero? left)
+ (length lst)
+ (iter (blink lst '()) (- left 1))))
+ (iter nums 25))
+
+(define memo (make-hash-table))
+
+(define (next0 num)
+ (if (zero? num)
+ (list 1)
+ (let* ((s (number->string num))
+ (len (string-length s)))
+ (if (even? len)
+ (list (string->number (substring s 0 (/ len 2)))
+ (string->number (substring s (/ len 2))))
+ (list (* num 2024))))))
+
+(define (next num)
+ (define val (hashv-ref memo num))
+ (if val
+ val
+ (let ((comp (next0 num)))
+ (hashv-set! memo num comp)
+ comp)))
+
+(define (step ht)
+ (define new (make-hash-table))
+ (hash-for-each
+ (lambda (num amt)
+ (for-each
+ (lambda (v)
+ (hashv-set! new v
+ (+ (hashv-ref new v 0) amt)))
+ (next num)))
+ ht)
+ new)
+
+(define (part2 port)
+ (define line (read-line port))
+ (define nums (map string->number (string-split line #\space)))
+ (define ht (make-hash-table))
+ (for-each (lambda (n)
+ (hashv-set! ht n
+ (+ 1 (hashv-ref ht n 0))))
+ nums)
+ (define (iter ht left)
+ (if (zero? left)
+ (let ((cnt 0))
+ (hash-for-each (lambda (k v) (set! cnt (+ cnt v)))
+ ht)
+ cnt)
+ (iter (step ht) (- left 1))))
+ (iter ht 75))