Advent of Code Day 3

06 Dec, 2020 - 14:12:31

By

Matthew Deig

Current Status

As of this post I only did Day 1, 2, and 3. The current day for this is Day 6. I been doing this at my own pace. I feel like I’m getting better with lisp with these puzzles, and I had to look at other people’s solutions to fully understand what the problem was asking for.

Day 3

Day 3 has you finding out how many trees you hit on a toboggan stuck on one path

here is the code

(defparameter *toboggan-vel* '((1 1) (3 1) (5 1) (7 1) (1 2)))

(defun read-file-in (filename)
  (with-open-file ( in filename
                       :if-does-not-exist nil
                       :external-format '(:utf-8 :replacement "?"))
    (loop for line = ( read-line in nil nil )
          while line collect line)))


(defun is-tree? (pos-char)
  (if (char= pos-char #\#) t))

(defun toboggan-y-vel (lines vel)
  (cond ((eq lines nil) '())
        ((= vel 0) lines)
        (t (toboggan-y-vel (cdr lines) (- vel 1)))))


(defun check-toboggan-path (lines pos)
  (cond ((eq lines nil) '())
        ((not (is-tree? (char (subseq (car lines) pos (+ pos 1)) 0))) (cons #\O (check-toboggan-path (cdr lines) (mod (+ pos *toboggan-x-vel*) (length (car lines))))))
        ((is-tree? (char (subseq (car lines) pos (+ pos 1)) 0)) (cons #\X (check-toboggan-path (cdr lines) (mod (+ pos *toboggan-x-vel*) (length (car lines))))))
        (t '())))

(defun check-toboggan-path-2 (lines pos y-vel x-vel)
  (cond ((eq lines nil) '())
        ((not (is-tree? (char (subseq (car lines) pos (+ pos 1)) 0)))
         (cons #\O
               (check-toboggan-path-2 (toboggan-y-vel lines y-vel) (mod (+ pos x-vel) (length (car lines))) y-vel x-vel)))
        ((is-tree? (char (subseq (car lines) pos (+ pos 1)) 0))
         (cons #\X (check-toboggan-path-2 (toboggan-y-vel lines y-vel) (mod (+ pos x-vel) (length (car lines))) y-vel x-vel)))
        (t '())))

(defun count-tree-hits (path)
  (loop for item in path
        when (char= item #\X)
          sum 1 into total
        finally (return total)))

(defun mul-tree-hit-counts (tree-hit-list)
  (cond ((eq tree-hit-list nil) 1)
        (t (* (car tree-hit-list) (mul-tree-hit-counts (cdr tree-hit-list))))))

(defun loop-vel ()
  (loop for item in *toboggan-vel*
        collect (count-tree-hits (check-toboggan-path-2 (read-file-in "puz3.in") 0 (cadr item) (car item)))))