# AOC2021 Puzzle 4 Python Solution

unknown
python
3 years ago
3.0 kB
1
Indexable
Never
```# Code for advent of code 2021 puzzle 4_1 and 4_2

class Bingo:
def __init__(self, bingo_input: list):
self.numbers = bingo_input[0].split(",")
self.boards = self.boards_from_input(bingo_input[2:])
self.winning_boards = []

def boards_from_input(self, bingo_board_list):
boards = []
board_lines = []
for line in bingo_board_list:
line = line.strip().split(" ")
line = [val for val in line if val != ""]
if line:
board_lines.append(line)
else:
boards.append(Board(board_lines))
board_lines = []
return boards

def get_first_winning_board(self):
for number in self.numbers:
for i in range(len(self.boards)):
self.boards[i].check_number(number)
if self.boards[i].is_complete():
self.boards[i].get_score(number)
return self.boards[i]

def get_winning_boards(self):
for number in self.numbers:
for i in range(len(self.boards)):
if not self.boards[i].score:
self.boards[i].check_number(number)
if self.boards[i].is_complete():
self.boards[i].get_score(number)
self.winning_boards.append(self.boards[i])
return self.winning_boards

class Board:
def __init__(self, board_lines: list):
self.shape = (len(board_lines), len(board_lines[0]))
self.board = board_lines
self.state_board = [[False for val in line] for line in self.board]
self.score = None

def check_number(self, number):
for i, line in enumerate(self.board):
try:
self.update_board(i, line.index(number))
break
except:
next

def update_board(self, i, j):
self.state_board[i][j] = True

def is_complete(self):
for line in self.state_board:
if all(line):
return True
for i in range(self.shape[1]):
if all([line[i] for line in self.state_board]):
return True
return False

def get_score(self, number):
if not self.score:
sum = 0
for i in range(self.shape[0]):
for j in range(self.shape[1]):
if not self.state_board[i][j]:
sum += int(self.board[i][j])
self.score = sum * int(number)

if __name__ == "__main__":