Day 4: Printing Department

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] 2 points 10 months ago

Python

Send in the object orientation!
Honestly though, it was just a convenient way to keep things contained.

from pathlib import Path


class Grid:
    def __init__(self, input: str) -> None:
        self.grid = list(map(lambda l: list(map(lambda c: 1 if c == "@" else 0, l)), input.splitlines()))
        self.dims = (len(self.grid[0]), len(self.grid))

    def get(self, x: int, y: int) -> int:
        if x < 0 or x >= self.dims[0] or y < 0 or y >= self.dims[1]:
            return 0
        return self.grid[x][y]

    def set(self, x: int, y: int, value: int):
        self.grid[x][y] = value

    def is_accessible(self, x: int, y: int) -> bool:
        if self.get(x, y):
            return sum(map(lambda t: self.get(*t), [(ix, iy) for ix in range(x - 1, x + 2) for iy in range(y - 1, y + 2)])) - 1 < 4
        return False


def part_one(input: str) -> int:
    grid = Grid(input)
    return len(list(filter(None, map(lambda t: grid.is_accessible(*t), [(x, y) for x in range(grid.dims[0]) for y in range(grid.dims[1])]))))


def part_two(input: str) -> int:
    grid = Grid(input)
    total = 0
    while True:
        remove = list(filter(None, map(lambda t: t if grid.is_accessible(*t) else None, [(x, y) for x in range(grid.dims[0]) for y in range(grid.dims[1])])))
        total += len(remove)
        if remove:
            [grid.set(*t, 0) for t in remove]
        else:
            break
    return total


if __name__ == "__main__":
    input = Path("_2025/_4/input").read_text("utf-8")
    print(part_one(input))
    print(part_two(input))
  • source