advent-of-code-2023

My solutions to AoC 2023
git clone git://git.entf.net/advent-of-code-2023
Log | Files | Refs

commit 26d88425d50f7ac6e88bdc6ac4a56b086936c237
parent 18f9b31f566e703414cb134be40c59a4abc0168d
Author: Lukas Henkel <lh@entf.net>
Date:   Fri,  1 Dec 2023 07:12:31 +0100

Day 1 task 2

Diffstat:
Msrc/day-1.lisp | 52++++++++++++++++++++++++++++++++++++++++++++++++----
Mt/day-1.lisp | 11++++++++++-
2 files changed, 58 insertions(+), 5 deletions(-)

diff --git a/src/day-1.lisp b/src/day-1.lisp @@ -9,14 +9,58 @@ do (return (char-number char)))) (defun last-digit (line) - (loop for i from (- (length line) 1) downto 0 + (loop for i from (1- (length line)) downto 0 for char = (aref line i) when (digit-char-p char) do (return (char-number char)))) +(defparameter *alpha-digit-table* '(("one" . 1) + ("two" . 2) + ("three" . 3) + ("four" . 4) + ("five" . 5) + ("six" . 6) + ("seven" . 7) + ("eight" . 8) + ("nine" . 9))) + +(defun alpha-digit-at (line start) + (loop for (compare . digit) in *alpha-digit-table* + when (loop for i from start below (min (length line) + (+ start (length compare))) + for ci from 0 + always (char= (aref line i) + (aref compare ci))) + do (return digit))) + +(defun reverse-alpha-digit-at (line end) + (loop for (compare . digit) in *alpha-digit-table* + for compare-length = (1- (length compare)) + when (loop for i from end downto (max (- end compare-length) 0) + for ci downfrom compare-length + always (char= (aref line i) + (aref compare ci))) + do (return digit))) + +(defun first-digit-alpha (line) + (loop for i from 0 below (length line) + for char = (aref line i) + when (digit-char-p char) + do (return (char-number char)) + thereis (alpha-digit-at line i))) + +(defun last-digit-alpha (line) + (loop for i from (1- (length line)) downto 0 + for char = (aref line i) + when (digit-char-p char) + do (return (char-number char)) + thereis (reverse-alpha-digit-at line i))) + (defun day-1 (input) (loop for line in (read-input input) while line - sum (parse-integer (format nil "~A~A" - (first-digit line) - (last-digit line))))) + sum (+ (* (or (first-digit line) 0) 10) + (or (last-digit line) 0)) into task-1 + sum (+ (* (first-digit-alpha line) 10) + (last-digit-alpha line)) into task-2 + finally (return (values task-1 task-2)))) diff --git a/t/day-1.lisp b/t/day-1.lisp @@ -8,4 +8,13 @@ (aoc:run-day 1 "1abc2 pqr3stu8vwx a1b2c3d4e5f -treb7uchet"))) +treb7uchet")) + + (assert= 281 + (nth-value 1 (aoc:run-day 1 "two1nine +eightwothree +abcone2threexyz +xtwone3four +4nineeightseven2 +zoneight234 +7pqrstsixteen"))))