-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart1.py
70 lines (53 loc) · 1.74 KB
/
part1.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from dataclasses import dataclass
from pathlib import Path
@dataclass
class Board:
grid: list[list[int]]
marked: list[list[bool]]
def mark_number(self, n: int) -> None:
for y in range(len(self.grid)):
for x in range(len(self.grid[y])):
if self.grid[y][x] == n:
self.marked[y][x] = True
def is_winning(self) -> bool:
for y in range(len(self.grid)):
if all(m for m in self.marked[y]):
return True
for x in range(len(self.grid[0])):
if all(self.marked[y][x] for y in range(len(self.grid))):
return True
return False
def score(self) -> int:
score = 0
for y in range(len(self.grid)):
for x in range(len(self.grid[y])):
if not self.marked[y][x]:
score += self.grid[y][x]
return score
with Path(Path(__file__).parent, "input").open() as f:
lines = [line.rstrip("\n") for line in f]
numbers_to_draw = list(map(int, lines[0].split(",")))
boards: list[Board] = []
board: Board = None # type: ignore
for line in lines[1:]:
if line == "":
if board is not None:
boards.append(board)
board = Board([], [])
continue
numbers_row = list(map(int, filter(lambda n: n != "", line.split(" "))))
board.grid.append(numbers_row)
board.marked.append([False for _ in range(len(numbers_row))])
boards.append(board)
finished = False
score = 0
for number in numbers_to_draw:
for board in boards:
board.mark_number(number)
if board.is_winning():
score = number * board.score()
finished = True
break
if finished:
break
print(f"Result: {score}")