Advent of Code 2023: Day 1

This post is part of a number that I've written as I complete Advent of Code exercises. The purpose is to practice taking notes for other people as I solve a problem, and to get used to writing and publishing a post on a nearly daily basis.

Part 1

This one is a text processing problem. You scan each line, and concatenate the first digit with the last digit, then sum each line to get your answer.

1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet

The edge case my first implementation ran into was when a line only has one digit, my indexing logic assumed that there would always be two numbers per line. Of course that if there's only one, it is both the first and last digit. With that fixed I found my answer.

Part 2

Now we have to consider numbers that are spelled out as well:

two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen

For the first line the number would be 29. The best approach I can think up for this one is to break up a line into chunks of individual digits and sequences of letters, then search those sequences of letters for spelled out numbers.

For the implementation I could see people making some sort of mixed digit/letter number iterator. For ours we're going to scan the line one by one, toss found digits into a list, transforming any spelled out ones into numbers as well. Then from there we just grab the first and last entry.

To break our chunks of letters into single digits, we're going to iterate forwards through the list and check against a lookup table of our spelled out digits 0-9. There's lots of room for performance improvements here.

Overlapping digits

I made an assumption that spelled out digits would not overlap, looking through some logs of the parsing results, nothing obvious stands out and I'm being told that I have the wrong answer. I do see this entry in my logging though:

info: line: sjtwonesix6cqbv4 info: list: 2664

Here there's the sub-string twonesix and it's being parsed as 26. I bet that they want that parsed as 216.

That did the trick.