From f87c4b6aaffb9e4dff4f963fa0e3ac317dbf3326 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Sat, 5 Dec 2020 13:17:36 +0100 Subject: [PATCH] 5 --- solutions/5/README.md | 13 ++++++++++ solutions/5/python/main.py | 51 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 solutions/5/README.md create mode 100644 solutions/5/python/main.py diff --git a/solutions/5/README.md b/solutions/5/README.md new file mode 100644 index 0000000..312a705 --- /dev/null +++ b/solutions/5/README.md @@ -0,0 +1,13 @@ +# 5 + +For the first one we treat the codes as 2 binary codes. One 7 and the other 3 long. + +The second tripped me up as I was returning the binary encoded ticket number but AOC was expecting the seat ID. My bad, took me long to get it. Thanks to @tcq1 + +
+ Solutions +
    +
  1. 998
  2. +
  3. 84, 4 -> 676
  4. +
+
diff --git a/solutions/5/python/main.py b/solutions/5/python/main.py new file mode 100644 index 0000000..7b2c666 --- /dev/null +++ b/solutions/5/python/main.py @@ -0,0 +1,51 @@ +from os.path import join, dirname +from itertools import product +from typing import Tuple + + +def from_binary(code: str, high: str) -> int: + return int(''.join([ + '1' if char == high else '0' + for char in code + ]), 2) + + +def read_seat(seat) -> Tuple[int, int]: + row_raw = seat[:-3] + column_raw = seat[-3:] + row = from_binary(row_raw, 'B') + column = from_binary(column_raw, 'R') + return row, column + + +def seat_code(row: int, column: int) -> int: + return row * 8 + column + + +data = join(dirname(__file__), '../data.txt') +with open(data) as f: + seats = f.read().strip().split('\n') + + free = list(product(range(4, 126), range(8))) + maximum = 0 + for seat in seats: + row, column = read_seat(seat) + m = row * 8 + column + maximum = max(maximum, m) + free.remove((row, column)) + + print(f"Highers ID:\t{maximum}") + + # Find the remaining seat + row_max = 0 + row_min = 128 + for row, _ in free: + row_max = max(row_max, row) + row_min = min(row_min, row) + remaining = [ + (row, column) + for row, column in free + if row >= row_min + 1 and row <= row_max - 2 + ][0] + my_ticket = seat_code(*remaining) + print(f"My Ticket:\t{my_ticket}")