]> git.friedersdorff.com Git - max/advent_of_code_2021.git/blob - 4_2.py
Try day 14
[max/advent_of_code_2021.git] / 4_2.py
1 """Play bingo"""
2 import sys
3
4 class BingoBoard():
5     def __init__(self, lines):
6         self.board = []
7         self.called = [
8             [False] * 5,
9             [False] * 5,
10             [False] * 5,
11             [False] * 5,
12             [False] * 5,
13         ]
14         for line in lines:
15             self.board.append([int(n) for n in line.strip().split()])
16
17     def number_called(self, number):
18         for i, row in enumerate(self.board):
19             for j, n in enumerate(row):
20                 if n == number:
21                     self.called[i][j] = True
22
23                     return self.won()
24
25         return False
26
27     def won(self):
28         for i, row in enumerate(self.called):
29             if row == [True] * 5:
30                 return True
31
32         cols_called = list(zip(*self.called))
33         cols_board = list(zip(*self.board))
34         for j, col in enumerate(cols_called):
35             if col == tuple([True] * 5):
36                 return True
37
38         return False
39
40     def get_score(self):
41         score = 0
42         for i in range(5):
43             for j in range(5):
44                 if not self.called[i][j]:
45                     score += self.board[i][j]
46                     print(self.board[i][j])
47
48         return score
49
50
51 bingo_boards = []
52 with open("4_input.txt") as f:
53     bingo_calls = [int(n) for n in f.readline().split(",")]
54
55     lines = f.readlines()
56     for i in range(0, len(lines), 6):
57         bingo_boards.append(BingoBoard(lines[i+1:i+6]))
58
59 for call in bingo_calls:
60     to_keep = []
61     for board in bingo_boards:
62         won = board.number_called(call)
63         if won:
64             if len(bingo_boards) == 1:
65                 score = board.get_score()
66                 print(score)
67                 print(call)
68                 print(score * call)
69                 sys.exit(0)
70         else:
71             to_keep.append(board)
72
73     bingo_boards = to_keep
74     to_keep = []