Skip to content

Advent of Code 2023 - Day 2

Posted on:December 5, 2023 at 03:22 PM at 1 min read

Solutions to Advent of Code 2023 (Day 2)

Part 1

def getIdIfValid(row):
    game, results = row.split(":")
    id = game.split(" ")[1]
    sets = results.strip().split("; ")

    allowed = {"red": 12, "green": 13, "blue": 14}
    for cube_set in sets:
        pulls = cube_set.split(", ")
        for pull in pulls:
            count, color = pull.split(" ")
            if int(count) > allowed[color]:
                return 0

    return int(id)


if __name__ == "__main__":
    with open("day_02.in") as f:
        data = f.read().strip().splitlines()

    total = 0
    for row in range(len(data)):
        total += getIdIfValid(data[row])

    print(total)

Part 2

def minNumberOfCubes(row):
    results = row.split(":")[1]
    sets = results.strip().split("; ")

    counter = {"red": 0, "green": 0, "blue": 0}
    for cube_set in sets:
        pulls = cube_set.split(", ")
        for pull in pulls:
            count, color = pull.split(" ")
            counter[color] = max(counter[color], int(count))

    return counter


if __name__ == "__main__":
    with open("day_02.in") as f:
        data = f.read().strip().splitlines()

    total = 0
    for row in range(len(data)):
        mul = 1
        mins = minNumberOfCubes(data[row])
        for v in mins.values():
            mul *= v
        total += mul

    print(total)

Comments