-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadvent-05.py
91 lines (69 loc) · 2.54 KB
/
advent-05.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
"""
URL for challenge: https://adventofcode.com/2020/day/5
"""
from itertools import product
def process_input():
"""
Upper/lower half can be thought of as
switching on/off a bit.
Generate binary numbers for the seat rows
and columns based on whether a letter
corresponds to upper half or lower half.
"""
f = open("advent-05-input.txt")
seat_rows, seat_cols = [], []
for line in f.readlines():
seat = line.strip()
row_code = seat[:7]
binary_row = ["1" if x == "B" else "0" for x in row_code]
seat_rows.append(int(''.join(binary_row), 2))
col_code = seat[7:]
binary_col = ["1" if x == "R" else "0" for x in col_code]
seat_cols.append(int(''.join(binary_col), 2))
return seat_rows, seat_cols
def part1():
seat_rows, seat_cols = process_input()
highest_seat_id = 0
for row, col in zip(seat_rows, seat_cols):
seat_id = row * 8 + col
if seat_id > highest_seat_id:
highest_seat_id = seat_id
return highest_seat_id
def part2():
seat_rows, seat_cols = process_input()
num_rows, num_cols = 128, 8
# Generate a grid with all
# the possible seat IDs.
all_seat_ids = [[row * num_cols + col for col in range(num_cols)]
for row in range(num_rows)]
# Empty out all the seats that
# are a part of the puzzle input.
for row, col in zip(seat_rows, seat_cols):
all_seat_ids[row][col] = 0
# The missing seat will be non-empty. Since
# its neighbours are also a part of the puzzle
# input, the neighbours will now be empty.
missing_seat = 0
for row, col in product(range(num_rows), range(num_cols)):
if is_missing_seat(all_seat_ids, row, col):
missing_seat = row * num_cols + col
break
return missing_seat
def is_missing_seat(all_seat_ids, row, col):
num_rows, num_cols = 128, 8
non_empty_seat = all_seat_ids[row][col] != 0
empty_above = row - 1 >= 0 and all_seat_ids[row-1][col] == 0
empty_right = col + 1 < num_cols and all_seat_ids[row][col+1] == 0
empty_below = row + 1 < num_rows and all_seat_ids[row+1][col] == 0
empty_left = col - 1 >= 0 and all_seat_ids[row][col-1] == 0
return all([non_empty_seat, empty_above, empty_right, empty_below, empty_left])
def run():
chall = int(input("Please enter either 1 or 2 for the challenges: "))
if chall == 1:
print(part1())
elif chall == 2:
print(part2())
else:
print("You need to enter either 1 or 2")
exit(1)
run()