advent-of-code

Perserverance, or the lack thereof

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

day01.scm (2145B)

    1 (use-modules (ice-9 popen))
    2 (use-modules (ice-9 rdelim))
    3 (use-modules (ice-9 format))
    4 
    5 (define (first-num line)
    6   (if line
    7       (let ((x (car line)))
    8         (if (char-numeric? x)
    9             (- (char->integer x) (char->integer #\0))
   10             (first-num (cdr line))))))
   11 
   12 (define (extract-num line)
   13   (+ (* (first-num line) 10)
   14      (first-num (reverse line))))
   15 
   16 (let ((file (open-input-file "input.txt")) (tot 0))
   17   (while #t
   18          (let ((line (car (%read-line file))))
   19            (if (eof-object? line)
   20                (break)
   21                (set! tot (+ tot (extract-num (string->list line)))))))
   22   ;; 53334
   23   (format #t "Part 1: ~d" tot)
   24   (newline))
   25 
   26 (define (match-prefix line word rev)
   27   (if rev (set! word (reverse word)))
   28   (cond ((null? word) #t)
   29         ((null? line) #f)
   30         (#t (and (eq? (car line) (car word))
   31                  (match-prefix (cdr line) (cdr word) #f)))))
   32 
   33 (define (to-word-digit line rev)
   34   (cond ((match-prefix line (string->list "one") rev) 1)
   35         ((match-prefix line (string->list "two") rev) 2)
   36         ((match-prefix line (string->list "three") rev) 3)
   37         ((match-prefix line (string->list "four") rev) 4)
   38         ((match-prefix line (string->list "five") rev) 5)
   39         ((match-prefix line (string->list "six") rev) 6)
   40         ((match-prefix line (string->list "seven") rev) 7)
   41         ((match-prefix line (string->list "eight") rev) 8)
   42         ((match-prefix line (string->list "nine") rev) 9)
   43         (#t #nil)))
   44 
   45 
   46 (define (first-num-2 line rev)
   47   (if line
   48       (let ((x (car line))
   49             (xx (to-word-digit line rev)))
   50         (cond ((char-numeric? x) (- (char->integer x) (char->integer #\0)))
   51               (xx xx)
   52               (#t (first-num-2 (cdr line) rev))))
   53       #nil))
   54 
   55 (define (extract-num-2 line)
   56   (+ (* (first-num-2 line #f) 10)
   57      (first-num-2 (reverse line) #t)))
   58 
   59 (let ((file (open-input-file "input.txt")) (tot 0))
   60   (while #t
   61          (let ((line (car (%read-line file))))
   62            (if (eof-object? line)
   63                (break)
   64                (set! tot (+ tot (extract-num-2 (string->list line)))))))
   65   ;; 52834
   66   (format #t "Part 2: ~d" tot)
   67   (newline))