aboutsummaryrefslogtreecommitdiffstats
path: root/2020/day05/binary-bording.py
blob: d3cb2844fb6e2ef9d1b7ed907966979a58e2ca49 (plain) (blame)
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
from typing import NamedTuple

EXAMPLES = [
    ('FBFBBFFRLR', 44, 5, 357),
    ('BFFFBBFRRR', 70, 7, 567),
    ('FFFBBBFRRR', 14, 7, 119),
    ('BBFFBBFRLL', 102, 4, 820)
]

class Seat(NamedTuple):
    row: int
    seat: int

    @property
    def seat_id(self) -> int:
        return self.row * 8 + self.seat

def boarding(seat: str) -> Seat:
    """given a string return the seat number"""
    row = 0
    for i, c in enumerate(reversed(seat[:7])):
        row += 1 << i * {'B': 1, 'F': 0}[c]
    row -= 1 * seat.count('F')

    col = 0
    for i, c in enumerate(reversed(seat[-3:])):
        col += 1 << i * {'L': 0, 'R': 1}[c]
    col -= 1 * seat.count('L')

    return Seat(row, col)

for eg, row, col, sid in EXAMPLES:
    s = Seat(*boarding(eg))
    assert row == s.row, f'{eg}: {row} != {s.row}'
    assert col == s.seat, f'{eg}: {col} != {s.seat}'
    assert sid == s.seat_id, f'{eg}: {sid} != {s.seat_id}'

with open('data/boarding-passes.txt') as f:
    seats = (boarding(bp.strip()) for bp in f)
    hi = max(bp.seat_id for bp in seats)

print(f'biggest seat: {hi}')