66 lines
1.8 KiB
Python
Executable File
66 lines
1.8 KiB
Python
Executable File
#! /usr/bin/env python3
|
|
from collections import namedtuple
|
|
|
|
|
|
Seat = namedtuple("Seat", ["row", "column", "id"])
|
|
|
|
|
|
def partition_search(partitions, start, end, lower, upper):
|
|
if start == end:
|
|
return start
|
|
assert partitions
|
|
assert start < end
|
|
assert all((lower, upper))
|
|
# print(f"Searching: range {start}:{end} {partitions[0]}")
|
|
|
|
mid = (end - start) / 2
|
|
direction = partitions.pop(0)
|
|
if direction == lower:
|
|
return partition_search(partitions, start, start + mid - .5, lower, upper)
|
|
elif direction == upper:
|
|
return partition_search(partitions, start + mid + .5, end, lower, upper)
|
|
|
|
raise ValueError(f"Unknown direction {direction}")
|
|
|
|
|
|
def parse_seat(code, total_rows=128, total_cols=8):
|
|
if len(code) != 10:
|
|
raise ValueError(f"Invalid code length: {code}")
|
|
row_partitions = list(code[:7])
|
|
row = partition_search(row_partitions, 0, total_rows-1, "F", "B")
|
|
col_partitions = list(code[7:])
|
|
col = partition_search(col_partitions, 0, total_cols-1, "L", "R")
|
|
return Seat(int(row), int(col), int(row*8+col))
|
|
|
|
|
|
def part1():
|
|
with open("input.txt") as f:
|
|
max_seat = max((parse_seat(line.strip()).id
|
|
for line in f))
|
|
print(f"Max seat id: {max_seat}")
|
|
|
|
|
|
def part2():
|
|
seats = []
|
|
with open("input.txt") as f:
|
|
seats = list(sorted((parse_seat(line.strip()).id
|
|
for line in f)))
|
|
last_id = None
|
|
for id in seats:
|
|
# print("Seat:", id)
|
|
if last_id is None:
|
|
last_id = id
|
|
continue
|
|
if id == last_id + 2:
|
|
print(f"My seat: {last_id+1}")
|
|
return
|
|
last_id = id
|
|
else:
|
|
print("Didn't find seat")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# print(parse_seat("FBFBBFFRLR"))
|
|
part1()
|
|
part2()
|