advent-of-code
Perserverance, or the lack thereof
git clone git://git.shimmy1996.com/advent-of-code.git
day02.scm (1974B)
1 (use-modules (ice-9 popen))
2 (use-modules (ice-9 rdelim))
3 (use-modules (ice-9 format))
4 (use-modules (ice-9 regex))
5 (use-modules (srfi srfi-1))
6
7 (define (extract-set-count set)
8 (let ((r (string-match " ([0-9]+) red" set))
9 (g (string-match " ([0-9]+) green" set))
10 (b (string-match " ([0-9]+) blue" set)))
11 (list (if r (string->number (regexp-substitute #f r 1)) 0)
12 (if g (string->number (regexp-substitute #f g 1)) 0)
13 (if b (string->number (regexp-substitute #f b 1)) 0))))
14
15 (define (is-set-possible set bag)
16 (reduce (lambda (a b) (and a b)) #t (map <= set bag)))
17
18 (define (is-game-possible game bag)
19 (let* ((tmp (string-split game #\:))
20 (game-id (string->number
21 (regexp-substitute #f (string-match "Game ([0-9]+)" (car tmp)) 1)))
22 (game-possible (fold (lambda (set res)
23 (and res (is-set-possible (extract-set-count set) bag)))
24 #t
25 (string-split (car (cdr tmp)) #\;))))
26 (if game-possible game-id 0)))
27
28 (let ((file (open-input-file "input.txt")) (tot 0))
29 (while #t
30 (let ((line (car (%read-line file))))
31 (if (eof-object? line)
32 (break)
33 (set! tot (+ tot (is-game-possible line '(12 13 14)))))))
34 ;; 2085
35 (format #t "Part 1: ~d" tot)
36 (newline))
37
38 (define (get-game-power game)
39 (let* ((set-counts (map extract-set-count
40 (string-split (car (cdr (string-split game #\:))) #\;)))
41 (min-bag (fold (lambda (next curr) (map max next curr))
42 '(0 0 0)
43 set-counts)))
44 (reduce * 1 min-bag)))
45
46 (let ((file (open-input-file "input.txt")) (tot 0))
47 (while #t
48 (let ((line (car (%read-line file))))
49 (if (eof-object? line)
50 (break)
51 (set! tot (+ tot (get-game-power line))))))
52 ;; 79315
53 (format #t "Part 2: ~d" tot)
54 (newline))