summaryrefslogtreecommitdiffstats
path: root/4.py
blob: 3cafb8b4c0f70286cb0c8658cf2251d5b5ab674e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from utils import open_day
from dataclasses import dataclass

@dataclass
class Cell:
    num: int
    marked: bool = False

def bingo(board):
    for row in board:
        if all(cell.marked for cell in row):
            return True
    for x in range(len(board[0])):
        if all(board[y][x].marked for y in range(len(board))):
            return True
    return False

def solve(nums, boards):
    won = set()
    wins = []
    for num in nums:
        for i, board in enumerate(boards):
            total = 0
            for row in board:
                for cell in row:
                    if cell.num == num:
                        cell.marked = True
                    if not cell.marked:
                        total += cell.num
            if i not in won and bingo(board):
                won.add(i)
                wins.append(num * total)
    return wins[0], wins[-1]

nums, *boards = open_day(4).read().rstrip().split('\n\n')
nums = list(map(int, nums.split(',')))
boards = [[[Cell(int(n)) for n in l.split()] for l in b.split('\n')] for b in boards]

part1, part2 = solve(nums, boards)
print(part1)
print(part2)