From 1e467d22eab4738daf5e90f855f98e898c52a8c2 Mon Sep 17 00:00:00 2001 From: Ted Cassirer Date: Tue, 9 Jan 2024 17:46:09 +0700 Subject: [PATCH] Day 18 --- aoc_cas/aoc2023/day18.py | 58 ++++++++++++++++++++++++++++++++++++++ tests/fixtures/2023/18.txt | 16 +++++++++++ 2 files changed, 74 insertions(+) create mode 100644 aoc_cas/aoc2023/day18.py create mode 100644 tests/fixtures/2023/18.txt diff --git a/aoc_cas/aoc2023/day18.py b/aoc_cas/aoc2023/day18.py new file mode 100644 index 0000000..2ecc99a --- /dev/null +++ b/aoc_cas/aoc2023/day18.py @@ -0,0 +1,58 @@ +from aoc_cas.common import Coordinate, DIR_RIGHT, DIR_DOWN, DIR_UP, DIR_LEFT, Direction + +directions: dict[str, Direction] = { + "U": DIR_UP, + "D": DIR_DOWN, + "R": DIR_RIGHT, + "L": DIR_LEFT, +} +directions_hexa = [ + DIR_RIGHT, + DIR_DOWN, + DIR_LEFT, + DIR_UP, +] + + +def parse_dig_coords(data: str, use_encoded: bool = False) -> tuple[list[Coordinate], int]: + coords: list[Coordinate] = [Coordinate.create(0, 0)] + total_distance = 0 + for line in data.splitlines(): + direction, k, encoded = line.split(" ") + if use_encoded: + distance_str = encoded[2:7] + dir_str = encoded[7] + dir = directions_hexa[int(dir_str, 16)] + distance = int(distance_str, 16) + else: + dir = directions[direction] + distance = int(k) + coords.append((coords[-1].move(dir, distance))) + total_distance += distance - 1 + # for _ in range(int(distance)): + # coords.append(coords[-1].move(dir)) + return coords[:-1], total_distance - 1 + + +def calculate_area(coords: list[Coordinate]) -> int: + shifted = coords[1:] + [coords[0]] + s1 = sum((c1.y + c2.y) * (c1.x - c2.x) for c1, c2 in zip(coords, shifted)) + return s1 // 2 + len(coords) // 2 + 1 + + +def part_a(data: str) -> int: + dig_coords, length = parse_dig_coords(data) + area = calculate_area(dig_coords) + return area + length // 2 + 1 + + +def part_b(data: str) -> int: + dig_coords, length = parse_dig_coords(data, use_encoded=True) + area = calculate_area(dig_coords) + return area + length // 2 + 1 + + +if __name__ == "__main__": + from aoc_cas.util import solve_with_examples + + solve_with_examples(year=2023, day=18) diff --git a/tests/fixtures/2023/18.txt b/tests/fixtures/2023/18.txt new file mode 100644 index 0000000..e22a810 --- /dev/null +++ b/tests/fixtures/2023/18.txt @@ -0,0 +1,16 @@ +R 6 (#70c710) +D 5 (#0dc571) +L 2 (#5713f0) +D 2 (#d2c081) +R 2 (#59c680) +D 2 (#411b91) +L 5 (#8ceee2) +U 2 (#caa173) +L 1 (#1b58a2) +U 2 (#caa171) +R 2 (#7807d2) +U 3 (#a77fa3) +L 2 (#015232) +U 2 (#7a21e3) +62 +952408144115 \ No newline at end of file