-
Notifications
You must be signed in to change notification settings - Fork 0
/
4b.py
121 lines (96 loc) · 2.91 KB
/
4b.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
from os import path
INPUT = path.join("input", "4.txt")
BOARD_SIZE = 5
class Tile:
def __init__(self, number) -> None:
self.number = number
self.marked = False
def check(self, number) -> bool:
if number == self.number:
self.marked = True
return True
return False
def __str__(self) -> str:
out_str = " "
if self.marked:
out_str = "*"
out_str += str(self.number).rjust(2)
return out_str
class Board:
def __init__(self, tiles) -> None:
self.tiles = tiles
self.won = False
def score_win(self) -> int:
unmarked = 0
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if not self.tiles[i][j].marked:
unmarked += self.tiles[i][j].number
return unmarked
def check_win(self) -> int:
if self.won:
return 0
win = False
# check rows
for i in range(BOARD_SIZE):
win = True
for j in range(BOARD_SIZE):
win = win and self.tiles[i][j].marked
if win:
print("Win in row " + str(i))
self.won = True
return self.score_win()
# check columns
for i in range(BOARD_SIZE):
win = True
for j in range(BOARD_SIZE):
win = win and self.tiles[j][i].marked
if win:
print("Win in column " + str(i))
self.won = True
return self.score_win()
return 0
def call_number(self, number) -> int:
marked = False
for row in self.tiles:
for tile in row:
marked = tile.check(number)
if marked:
return number * self.check_win()
return 0
def display(self) -> None:
out_str = ""
for row in self.tiles:
for tile in row:
out_str += str(tile)
out_str += "\n"
print(out_str)
def main() -> None:
in_lines = []
boards = []
with open(INPUT, "r") as in_file:
in_lines = in_file.read().splitlines()
called = [int(x) for x in in_lines[0].split(",")]
print(called)
tiles = []
for line in in_lines[2:]:
if line == "":
boards.append(Board(tiles))
tiles = []
else:
row = []
for i in range(0, len(line), 3):
row.append(Tile(int(line[i : i + 2])))
tiles.append(row)
boards.append(Board(tiles)) # do the last one
last_result = 0
for number in called:
print("Calling " + str(number))
for board in boards:
if not board.won:
result = board.call_number(number)
if result > 0:
last_result = result
print(last_result)
if __name__ == "__main__":
main()