day15.scm (2411B)
1 (use-modules (ice-9 popen))
2 (use-modules (ice-9 rdelim))
3 (use-modules (ice-9 format))
4 (use-modules (srfi srfi-1))
5
6 (define (parse-input filename)
7 (let ((file (open-input-file filename))
8 (init-seq '()))
9 (let ((line (car (%read-line file))))
10 (set! init-seq (string-split line #\,)))
11 init-seq))
12
13 (define (run-hash seq curr-val)
14 (if (null? seq)
15 curr-val
16 (run-hash (cdr seq)
17 (floor-remainder (* (+ curr-val (char->integer (car seq))) 17) 256))))
18
19 (let* ((init-seq (parse-input "input.txt"))
20 (hash-seq (map (lambda (x) (run-hash (string->list x) 0)) init-seq)))
21 ;; 510801
22 (format #t "Part 1: ~d" (fold + 0 hash-seq))
23 (newline))
24
25 (define (replace-or-add box key val)
26 (let ((i 0)
27 (i-max (length box))
28 (found #f))
29 (while (and (not found) (< i i-max))
30 (if (equal? (car (list-ref box i)) key)
31 (begin
32 (list-set! box i (cons key val))
33 (set! found #t)
34 (break)))
35 (set! i (1+ i)))
36 (if (not found)
37 (set! box (append box (list (cons key val)))))
38 box))
39
40 (define (remove-key box key)
41 (filter
42 (lambda (x) (not (equal? (car x) key)))
43 box))
44
45 (define (run-hashmap init-seq)
46 (let ((boxes (make-list 256 '())))
47 (map
48 (lambda (seq)
49 (if (string-index seq #\=)
50 (let* ((tmp (string-split seq #\=))
51 (key (car tmp))
52 (box-num (run-hash (string->list key) 0))
53 (val (string->number (car (cdr tmp)))))
54 (list-set! boxes box-num (replace-or-add (list-ref boxes box-num) key val)))
55 (let* ((tmp (string-split seq #\-))
56 (key (car tmp))
57 (box-num (run-hash (string->list key) 0)))
58 (list-set! boxes box-num (remove-key (list-ref boxes box-num) key))
59
60 )))
61 init-seq)
62 boxes))
63
64 (define (calc-focusing-power boxes)
65 (let ((tot-power 0))
66 (do ((i 0 (1+ i))) ((>= i (length boxes)))
67 (let ((box (list-ref boxes i)))
68 (do ((j 0 (1+ j))) ((>= j (length box)))
69 (set! tot-power
70 (+ tot-power (* (1+ i) (1+ j) (cdr (list-ref box j))))))))
71 tot-power))
72
73 (let* ((init-seq (parse-input "input.txt"))
74 (boxes (run-hashmap init-seq))
75 (tot-power (calc-focusing-power boxes)))
76 ;; 212763
77 (format #t "Part 2: ~d" tot-power)
78 (newline))