advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git

day06.scm (1795B)

    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         (time '())
   13         (distance '()))
   14     (let ((line (car (%read-line file))))
   15       (set! time (parse-numbers (car (cdr (string-split line #\:))))))
   16     (let ((line (car (%read-line file))))
   17       (set! distance (parse-numbers (car (cdr (string-split line #\:))))))
   18     (map cons time distance)))
   19 
   20 (define (solve-quadratic a b c)
   21   (let ((tmp (sqrt (- (expt b 2) (* 4 a c)))))
   22         (cons (/ (+ (- b) tmp) (* 2 a)) (/ (- (- b) tmp) (* 2 a)))))
   23 
   24 (define (count-record-beater time dist)
   25   (let ((res (solve-quadratic -1 time (- dist))))
   26     (inexact->exact (1+ (- (ceiling (1- (cdr res))) (floor (1+ (car res))))))))
   27 
   28 (let* ((input (parse-input "input.txt"))
   29        (res (fold * 1 (map (lambda (x) (count-record-beater (car x) (cdr x))) input))))
   30   ;; 4811940
   31   (format #t "Part 1: ~d" res)
   32   (newline))
   33 
   34 (define (parse-numbers-2 numbers)
   35   (string->number (list->string (filter char-numeric? (string->list numbers)))))
   36 
   37 (define (parse-input-2 filename)
   38   (let ((file (open-input-file filename))
   39         (time '())
   40         (distance '()))
   41     (let ((line (car (%read-line file))))
   42       (set! time (parse-numbers-2 (car (cdr (string-split line #\:))))))
   43     (let ((line (car (%read-line file))))
   44       (set! distance (parse-numbers-2 (car (cdr (string-split line #\:))))))
   45     (cons time distance)))
   46 
   47 (let* ((input (parse-input-2 "input.txt"))
   48        (res (count-record-beater (car input) (cdr input))))
   49   ;; 30077773
   50   (format #t "Part 2: ~d" res)
   51   (newline))