aocpy/2021/d4.py
2024-11-17 05:45:47 -05:00

53 lines
1.4 KiB
Python

from lib import get_data
from lib import ints
data = get_data(__file__).strip()
boards = []
numbers = None
for i, p in enumerate(data.split("\n\n")):
if i == 0:
numbers = ints(p)
else:
board = []
for line in p.splitlines():
board.append(ints(line))
boards.append(board)
assert numbers is not None
first_won = None
last_won = None
boards_done = list()
for n in numbers:
for i in range(len(boards)):
if i in boards_done:
continue
board = boards[i]
board = [[f if n != f else None for f in row] for row in board]
boards[i] = board
for row in board:
if all(cell is None for cell in row):
if not i in boards_done:
boards_done.append(i)
for col in zip(*board):
if all(cell is None for cell in col):
if not i in boards_done:
boards_done.append(i)
if len(boards_done) > 0 and first_won is None:
first_won = (i, n)
if len(boards_done) == len(boards):
last_won = (i, n)
break
if len(boards_done) == len(boards):
break
assert first_won is not None
assert last_won is not None
for i, n in [first_won, last_won]:
board = boards[i]
a = sum([sum([n if n is not None else 0 for n in row]) for row in board])
print(a * n)