aboutsummaryrefslogtreecommitdiff
path: root/day11.scm
blob: 76ca159b792c2208d287403e00dfcc2c0b717817 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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))