Advent Of Code '23 - day 01

Table of Contents

rough start

I should have started preparing things more in advance, but I seem to fail that kind stuf most of the time. And on top of all this, I got sick last night and didn't sleep all that well. Really bummed that I wasn't able to start solving the puzzles from the first minute.

I had already seen this first puzzle was harder then first day puzzles of previous years. There will probably be more elegant ways to solve these but for now I justed wanted to get them solved. I spent most of my time trying to get the regex match working, and fighting with my phone's keyboard. Yes, I coded this in Emacs running in Termux on my phone. Which isn't something I'd recommend anyone to do.

Part 1

Basically, I extract the first and last number from a single line using two seperate regexes. Each result is converted from two strings to a single number and finally summed together.

(defun aoc23/find-tuple (string)
  (let ((a (if (string-match "^.*?\\([0-9]\\)" string)
               (match-string 1 string)
             "-"))
        (b (if (string-match "^.*\\([0-9]\\)" string)
               (match-string 1 string)
             "-")))
    `(,a ,b)))

(defun aoc23/tuple-to-number (tuple)
  "convert tuple of two strings to a single number"
  (+ (* 10 (string-to-number (car tuple)))
     (string-to-number (cadr tuple))))

(apply '+ (mapcar (lambda (line)
                    (aoc23/tuple-to-number
                     (aoc23/find-tuple line)))
                  (split-string input)))

Part 2

Taking the easy route here as everything is already in place, save for a few minor details. The regexes are expanded with the words for each digit. The conversion to string is replaced with a version that understands the words.

(defun aoc23/find-tuple (string)
  (let* ((capt "[0-9]\\|one\\|two\\|three\\|four\\|five\\|six\\|seven\\|eight\\|nine\\|zero")
         (a (if (string-match (concat "^.*?\\(" capt "\\)") string)
                (match-string 1 string)
              "-"))

         (b (if (string-match (concat "^.*\\(" capt "\\)") string)
                (match-string 1 string)
              "-")))
    `(,a ,b)))

(defun aoc23/string-to-number (str)
  "convert string to number the ugly way"
  (let ((map '(("zero" . 0)
               ("one" . 1)
               ("two" . 2)
               ("three" . 3)
               ("four" . 4)
               ("five" . 5)
               ("six" . 6)
               ("seven" . 7)
               ("eight" . 8)
               ("nine" . 9)) )
        (n (string-to-number str)))
    (if (length= str 1)
        n
      (cdr (assoc str map)))))


(defun aoc23/tuple-to-number (tuple)
  "convert tuple of two strings to a single number"
  (+ (* 10 (aoc23/string-to-number (car tuple)))
     (aoc23/string-to-number (cadr tuple))))


(apply '+ (mapcar (lambda (line)
                    (aoc23/tuple-to-number (aoc23/find-tuple line)))
                  (split-string input)))