DEV Community

Cover image for Advent of Code 2023
Rob van der Leek
Rob van der Leek

Posted on • Edited on

Advent of Code 2023

In this series I'll share my progress with the 2023 version of Advent of Code.

I'll try to post my solution to the puzzle on the day it's unlocked on the website. Let's see how far I get this year (I've started many times before in previous years but never made it to December 25...)

My solutions are not the most sophisticated, or the smallest, or the fastest, etc. I only have an hour or so each day to work on the puzzles. Still, I hope you like reading along with my coding adventures, and perhaps compare your solutions with mine, let me know in the comments below!

You can also follow my progress on GitHub.

A bit on my setup

This year I'll be using Python. Mainly because this year I don't have the time to learn a new language (if you have a bit more time available, Advent of Code is a great way to learn a new programming language.) But also because Python is a beautiful language.

Rules I try to adhere to:

  • I write all the code in a single file (main.py) using VIM in a terminal
  • A solution should be less than 100 lines, if it's bigger I try to refactor/be smarter
  • I only use code from the standard Python library, no third-party libraries
  • I only use Google/StackOverflow for basic Python stuff

A screenshot of my terminal

December 1st

The puzzle of day 1 took me longer than expected. Not a soft landing this year πŸ˜„ but with those Elves I guess nothing will be easy this year 🀦

My pitfall for this puzzle: The sample input did not contain an example of an input my code did not support. It took me quite some time and a careful re-reading of the "requirements" to figure that out.

Solution here, do not click if you want to solve the puzzle first yourself
#!/usr/bin/env python3

substitutions = [('one', '1'), ('two', '2'), ('three', '3'), ('four', '4'), 
    ('five', '5'), ('six', '6'), ('seven', '7'), ('eight', '8'), ('nine', '9')]

def first_digit(s):
    index = 0
    while index < len(s):
        if s[index].isdigit():
            return s[index]
        for sub in substitutions:
            if s[index:].startswith(sub[0]):
                return sub[1]
        index += 1

def last_digit(s):
    index = len(s) - 1
    while index >= 0:
        if s[index].isdigit():
            return s[index]
        for sub in substitutions:
            if s[index:].startswith(sub[0]):
                return sub[1]
        index -= 1

with open('input2.txt') as infile:
    lines = [line.strip() for line in infile.readlines()]
numbers = []
for line in lines:
    number = int(f'{first_digit(line)}{last_digit(line)}')
    numbers.append(number)
print(sum(numbers))
Enter fullscreen mode Exit fullscreen mode

That's it! See you again tomorrow!

Top comments (0)