Day 4, Year 2021: Giant Squid
First read the problem description.
import numpy as np
class Board():
def __init__(self, size):
self.numbers = np.zeros((size, size), np.int32)
self.marks = np.zeros((size, size), bool)
def is_winner(self):
= self.marks.shape[0]
size for i in range(size):
if np.sum(self.marks[i]) == size or \
sum(self.marks[:,i]) == size:
np.
return True
def mark(self, n):
self.marks |= self.numbers == n
def sum_unmarked(self):
return np.sum(self.numbers * ~self.marks)
def parse_file(f):
= map(int, next(f).split(','))
numbers_drawn = None
board = []
boards
= 0
i
for l in f:
= l.rstrip()
l if l == "":
if board:
boards.append(board)= Board(5)
board = 0
i continue
= list(map(int, l.split()))
board.numbers[i] += 1
i
return numbers_drawn, boards
def find_winner(numbers_drawn, boards):
= None
first_winner_score = None
last_winner_score = list(numbers_drawn)
numbers_drawn for ni, n in enumerate(numbers_drawn):
for b in boards:
b.mark(n)
for bi, b in enumerate(boards):
if b.is_winner():
= None
boards[bi]
if first_winner_score is None:
= b.sum_unmarked() * n
first_winner_score
if len(boards) == 1:
= b.sum_unmarked() * n
last_winner_score
= [b for b in boards if b]
boards
return first_winner_score, last_winner_score
import import_ipynb
import helper
= helper.open_file('2021_4.txt')
f = parse_file(f) numbers_drawn, boards
find_winner(numbers_drawn, boards)
(64084, 12833)
Source code of the solution(s):