StyleInCode

RSS

 

Day 2 - Advent of Code 2025

2 December 2025

Working solutions for the day 2 puzzles.

Part One

""" day_02_01.py """

# usage: python3 day_02_01.py


def get(filename):
    """ contents of filename """
    with open(filename, 'r', encoding='utf-8') as infile:
        data = infile.read().strip()

    return data


def test(data, given_solution):
    """ testing """
    assert solve(data) == given_solution


def valid(text):
    """ is valid id """
    size = len(text)
    if size % 2 == 1:
        return True

    if text[:size // 2] != text[size // 2:]:
        return True

    return False


def invalid_id_list(x1, x2):
    """ identify invalid ids """
    return [i for i in range(int(x1), int(x2) + 1) if not valid(str(i))]


def solve(data):
    """ solve the puzzle """
    invalid_id_sum = 0

    for interval in data.split(','):
        [begin, end] = interval.split('-')
        invalid_id_sum += sum(invalid_id_list(begin, end))

    return invalid_id_sum


if __name__ == '__main__':
    test(get('example01'), 1227775554)

    puzzle = get('input')
    solution = solve(puzzle)

    print(solution)

Part Two

""" day_02_02.py """

# usage: python3 day_02_02.py

import re


def get(filename):
    """ contents of filename """
    with open(filename, 'r', encoding='utf-8') as infile:
        data = infile.read().strip()

    return data


def test(data, given_solution):
    """ testing """
    assert solve(data) == given_solution


def valid(text):
    """ is valid id """
    return not re.fullmatch(r'(.*)\1{1,}', text)


def invalid_id_list(x1, x2):
    """ identify invalid ids """
    return [i for i in range(int(x1), int(x2) + 1) if not valid(str(i))]


def solve(data):
    """ solve the puzzle """
    invalid_id_sum = 0

    for interval in data.split(','):
        [begin, end] = interval.split('-')
        invalid_id_sum += sum(invalid_id_list(begin, end))

    return invalid_id_sum


if __name__ == '__main__':
    test(get('example01'), 4174379265)

    puzzle = get('input')
    solution = solve(puzzle)

    print(solution)

Categories

Links