~noelle/aoc-2021

b29905d5e3667e91cd3413a6d26e0ea8ab7e6e1c — Noelle Leigh 2 years ago f7a30d5
13_2
1 files changed, 61 insertions(+), 0 deletions(-)

A 13/puzzle_2.py
A 13/puzzle_2.py => 13/puzzle_2.py +61 -0
@@ 0,0 1,61 @@
"""
Solution for AoC 2021 13 Puzzle 2

cat input.txt | python puzzle_2.py
"""
import sys

X = "x"
Y = "y"

def draw_points(points: list[tuple[int, int]]):
    max_x = max(map(lambda p: p[0], points))
    max_y = max(map(lambda p: p[1], points))

    for y in range(max_y + 1):
        for x in range(max_x + 1):
            char = "#" if (x, y) in points else " "
            sys.stdout.write(char)
        sys.stdout.write("\n")

def reflect(point: tuple[int, int], axis: str, coordinate: int):
    point_x, point_y = point
    if axis == Y:
        distance = point_y - coordinate
        if distance < 0:
            return point
        return (point_x, point_y - (2 * distance))

    if axis == X:
        distance = point_x - coordinate
        if distance < 0:
            return point
        return (point_x - (2 * distance), point_y)

    return point


if __name__ == "__main__":
    points: set[tuple[int, int]] = set()
    folds: list[tuple[str, int]] = []
    reading_points = True
    reading_folds = False
    for line in sys.stdin:
        line = line.strip()
        if not line:
            reading_points = False
            reading_folds = True
            continue
        if reading_points:
            points.add(tuple(map(int, line.split(",", maxsplit=1))))
            continue
        if reading_folds:
            axis, coordinate = line.removeprefix("fold along ").split("=", maxsplit=1)
            folds.append((axis, int(coordinate)))
            continue
    for fold_axis, fold_coordinate in folds:
        points = set(
            map(lambda point: reflect(point, fold_axis, fold_coordinate), points)
        )

    draw_points(points)