advent-of-code
Perserverance, or the lack thereof
git clone git://git.shimmy1996.com/advent-of-code.git
day09.scm (1473B)
1 (use-modules (ice-9 popen))
2 (use-modules (ice-9 rdelim))
3 (use-modules (ice-9 format))
4 (use-modules (ice-9 receive))
5 (use-modules (srfi srfi-1))
6
7 (define (parse-numbers numbers)
8 (filter (lambda (x) x) (map string->number (string-split numbers #\ ))))
9
10 (define (parse-input filename)
11 (let ((file (open-input-file filename))
12 (report '()))
13 (while #t
14 (let ((line (car (%read-line file))))
15 (if (eof-object? line)
16 (break)
17 (set! report (cons (parse-numbers line) report)))))
18 (reverse report)))
19
20 (define (all-zero history)
21 (if (null? history)
22 #t
23 (and (= (car history) 0) (all-zero (cdr history)))))
24
25 (define (calc-diff history)
26 (if (< (length history) 2)
27 '()
28 (cons (- (car (cdr history)) (car history))
29 (calc-diff (cdr history)))))
30
31 (define (extrapolate history)
32 (if (all-zero history)
33 0
34 (+ (car (last-pair history)) (extrapolate (calc-diff history)))))
35
36 (let* ((report (parse-input "input.txt"))
37 (extrapolated (map extrapolate report)))
38 ;; 1647269739
39 (format #t "Part 1: ~d" (reduce + #nil extrapolated))
40 (newline))
41
42 (define (backward-extrapolate history)
43 (if (all-zero history)
44 0
45 (- (car history) (backward-extrapolate (calc-diff history)))))
46
47 (let* ((report (parse-input "input.txt"))
48 (extrapolated (map backward-extrapolate report)))
49 ;; 864
50 (format #t "Part 2: ~d" (reduce + #nil extrapolated))
51 (newline))