adventofcode/2020/05/main.py
2022-12-02 09:41:56 +01:00

52 lines
1 KiB
Python

import math
def get(s, l, u, ltok, utok):
if l == u:
return l
c = s[:1]
h = math.ceil((u - l) / 2)
assert c in (ltok, utok)
if c == ltok:
return get(s[1:], l, u - h, ltok, utok)
return get(s[1:], l + h, u, ltok, utok)
def seat(s):
row = get(s[:7], 0, 127, "F", "B")
col = get(s[7:10], 0, 7, "L", "R")
return row, col
def seat_id(row, col):
return row * 8 + col
def missing_seat(seats):
a = sorted(seats)
b = range(a[0], a[-1])
missing = set(b) - set(a)
assert len(missing) == 1
return missing.pop()
assert seat("FBFBBFFRLR") == (44, 5)
assert seat("BFFFBBFRRR") == (70, 7)
assert seat_id(70, 7) == 567
assert seat("FFFBBBFRRR") == (14, 7)
assert seat_id(14, 7) == 119
assert seat("BBFFBBFRLL") == (102, 4)
assert seat_id(102, 4) == 820
assert seat("BBFBFBFLLL") == (106, 0)
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
seats = [seat_id(*seat(x.rstrip())) for x in lines]
sid_max = max(seats)
print(f"Highest seat ID: {sid_max}")
print(f"Your seat is : {missing_seat(seats)}")