summaryrefslogtreecommitdiff
path: root/2-2.scm
blob: 240d8d1cfc53b8f8087e845508181f73ba199a17 (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
#!/usr/bin/env -S guile -s
!#
(use-modules (ice-9 regex)
             (ice-9 textual-ports)
             (srfi srfi-1))

(define red-max 12)
(define green-max 13)
(define blue-max 14)

(define (read-lines port)
  (letrec ((loop (lambda (l ls)
                   (if (eof-object? l)
                       ls
                       (loop (get-line port) (cons l ls))))))
    (reverse (loop (get-line port) '()))))

(define (triplet-values triplet)
  (let* ((zero (string-match "(.)" "0"))
         (red (string->number (match:substring (or (string-match "([0-9]+) red" triplet) zero) 1)))
         (green (string->number (match:substring (or (string-match "([0-9]+) green" triplet) zero) 1)))
         (blue (string->number (match:substring (or (string-match "([0-9]+) blue" triplet) zero) 1))))
    `(,red ,green ,blue)))

(define (line-value line)
  (let* ((id-split (string-match "^Game ([0-9]+):(.*)$" line))
         (rest (string-split (match:substring id-split 2) #\;))
         (values (map triplet-values rest))
         (red-min (fold (lambda (x y) (if (> x y) x y)) 0 (map car values)))
         (green-min (fold (lambda (x y) (if (> x y) x y)) 0 (map cadr values)))
         (blue-min (fold (lambda (x y) (if (> x y) x y)) 0 (map caddr values)))
         (power (* red-min green-min blue-min)))
    power))

(let* ((port (open-input-file "2.txt"))
       (lines (read-lines port)))
  (close-port port)
  (display (fold + 0 (map line-value lines))))