-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
87 lines (61 loc) · 2.13 KB
/
solution.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
from time import time
from util.file_input_processor import read_lines
BOARD_SIZE = 5
DRAWN = -1
def read_board(lines):
return list(map(lambda line: list(map(int, line.split())), lines))
def read():
input_lines = read_lines()
numbers = list(map(int, input_lines[0].split(',')))
boards = []
for i in range(2, len(input_lines), BOARD_SIZE + 1):
boards.append(read_board(input_lines[i:i + BOARD_SIZE]))
return numbers, boards
def mark_number_on_boards(number, boards):
for board in boards:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == number:
board[i][j] = DRAWN
def check_if_winner(board):
# Check lines
for line in board:
if all(number == DRAWN for number in line):
return True
# Check columns
for column in range(BOARD_SIZE):
valid_column = True
for line in board:
if line[column] != DRAWN:
valid_column = False
break
if valid_column:
return True
return False
def sum_board(board):
return sum(map(lambda line: sum(filter(lambda number: number != DRAWN, line)), board))
def part_1():
numbers, boards = read()
for number in numbers:
mark_number_on_boards(number, boards)
winner = list(filter(check_if_winner, boards))
if winner:
return number * sum_board(winner[0])
def part_2():
numbers, boards = read()
for number in numbers:
mark_number_on_boards(number, boards)
winners = list(filter(check_if_winner, boards))
if winners:
boards = list(filter(lambda board: board not in winners, boards))
if len(boards) == 0:
return number * sum_board(winners[0])
if __name__ == "__main__":
start = time()
result_part_1 = part_1()
end = time()
print(f'Part 1 ran in {round(end - start, 2)} seconds and the result is {result_part_1}')
start = time()
result_part_2 = part_2()
end = time()
print(f'Part 2 ran in {round(end - start, 2)} seconds and the result is {result_part_2}')