Day 4 - Advent of Code 2023

Working solutions for the day 4 puzzles.

Part One

""" day_04_01.py """

# usage: python3 day_04_01.py < input

import sys


def process(text):
    """ card # and matches """
    label, game = text.split(': ')
    _, seq = label.split()
    x, y = game.split(' | ')
    return seq, len(set(x.split()) & set(y.split()))


answer = 0
for line in sys.stdin:
    _, matches = process(line)
    if matches > 0:
        answer += pow(2, matches - 1)

print(answer)

Part Two

""" day_04_02.py """

# usage: python3 day_04_02.py < input

import sys


def process(text):
    """ card # and matches """
    label, game = text.split(': ')
    _, seq = label.split()
    x, y = game.split(' | ')
    return seq, len(set(x.split()) & set(y.split()))


cards = {}
for line in sys.stdin:
    num, matches = process(line)
    cards[int(num)] = [1, matches]

for num, (qty, matches) in cards.items():
    for _ in range(qty):
        for i in range(num + 1, num + 1 + matches):
            cards[i][0] += 1

print(sum(i for i, _ in cards.values()))