Day 1: Trebuchet

 13th December 2023 at 12:57pm

Part 1

It's been a while since I programmed, and I took a long while to take up upon the first challenge.

The first part was was very straightforward, maybe with the duplication of one-digit number the only detail to keep in mind. I did not do TDD for the first day.

def create_number_from_digits(digits: list):
    return int(digits[0]) * 10 + int(digits[0 if len(digits) == 1 else -1])

with open("input") as file:
    data = file.read().strip().split('\n')

digits = map(lambda line: list(filter(lambda char: char.isdigit(),
                                      line)),
             data)

print(sum(map(lambda x: create_number_from_digits(x),
        digits)))

Part 2

As for part 2, it got a little trickier. Managing the overlapping case of two numbers (a line with 'twone', for example) was not immediate.

NBRS = (['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
        + list(digits))
pattern = '|'.join(NBRS)

def parse_number(number: str):
    return (int(number) if number.isdigit() 
            else NBRS.index(number) + 1)

# it handles the case where a single digit in a line
# must be converted into a double-digit; eg. 7 becomes 77.
def create_number_from_digits(digits: list):
    return (parse_number(digits[0]) * 10 + 
            parse_number(digits[0 if len(digits) == 1 else -1]))

with open("input") as file:
    data = file.read().strip().split('\n')

matched_numbers = map(lambda line: findall(pattern, line),
                      data)

print(sum(map(lambda x: create_number_from_digits(x),
              matched_numbers)))