|
| 1 | +# 'Advent of code' solution for year {year} day {day} |
| 2 | +import os |
| 3 | +import sys |
| 4 | + |
| 5 | +DIR_PATH = os.path.dirname(os.path.realpath(__file__)) |
| 6 | + |
| 7 | +def _get_input(): |
| 8 | + content = None |
| 9 | + if os.path.isfile(os.path.join(DIR_PATH, "input.txt")): |
| 10 | + with open(os.path.join(DIR_PATH, "input.txt"), "r", encoding="utf-8") as file: |
| 11 | + content = file.read().strip().splitlines() |
| 12 | + return content |
| 13 | + else: |
| 14 | + print("Error! Input file does not exist!") |
| 15 | + sys.exit() |
| 16 | + |
| 17 | +def rotate_dial(dial: list[int], amount: int) -> int: |
| 18 | + start = dial[50] |
| 19 | + count = 0 |
| 20 | + full_rotations = abs(amount) // len(dial) |
| 21 | + rest = abs(amount) % len(dial) |
| 22 | + |
| 23 | + passed_zero_in_partial = False |
| 24 | + if amount > 0: # Rotate Left |
| 25 | + index = amount % len(dial) |
| 26 | + |
| 27 | + for step in range(1, rest + 1): |
| 28 | + pos = (start + step) % len(dial) |
| 29 | + if pos == 0: |
| 30 | + passed_zero_in_partial = True |
| 31 | + else: # Rotate right |
| 32 | + index = len(dial) - ((-amount) % len(dial)) |
| 33 | + |
| 34 | + for step in range(1, rest + 1): |
| 35 | + pos = (start - step) % len(dial) |
| 36 | + if pos == 0: |
| 37 | + passed_zero_in_partial = True |
| 38 | + |
| 39 | + dial[:] = dial[index:] + dial[:index] |
| 40 | + |
| 41 | + count += full_rotations |
| 42 | + if passed_zero_in_partial: |
| 43 | + count += 1 |
| 44 | + elif dial[50] == 0: |
| 45 | + count += 1 |
| 46 | + return count |
| 47 | + |
| 48 | +def part_1(i: list[str]): |
| 49 | + dial = [i for i in range(100)] |
| 50 | + |
| 51 | + count = 0 |
| 52 | + for instruction in i: |
| 53 | + direction, amount = instruction[0], int(instruction[1:]) |
| 54 | + |
| 55 | + if direction == "R": |
| 56 | + amount = -amount |
| 57 | + |
| 58 | + rotate_dial(dial, amount) |
| 59 | + |
| 60 | + if dial[50] == 0: |
| 61 | + count += 1 |
| 62 | + |
| 63 | + print(f"[P1]: The password is: {count}") |
| 64 | + |
| 65 | +def part_2(i: list[str]): |
| 66 | + dial = [i for i in range(100)] |
| 67 | + |
| 68 | + count = 0 |
| 69 | + for instruction in i: |
| 70 | + direction, amount = instruction[0], int(instruction[1:]) |
| 71 | + |
| 72 | + if direction == "R": |
| 73 | + amount = -amount |
| 74 | + |
| 75 | + count += rotate_dial(dial, amount) |
| 76 | + |
| 77 | + print(f"[P2]: The password is: {count}") |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + inputs = _get_input() |
| 81 | + if not inputs: |
| 82 | + print("Error! Input file is empty!") |
| 83 | + sys.exit() |
| 84 | + |
| 85 | + part_1(inputs) |
| 86 | + part_2(inputs) |
| 87 | + |
| 88 | + sys.exit() |
0 commit comments