day13: massive speed-up by getting only active cells (already Coordinate()s) in a row/column from Grid()

This commit is contained in:
Stefan Harmuth 2021-12-13 11:11:37 +01:00
parent 1fd5b27944
commit 1d3df3bdb8

View File

@ -17,14 +17,16 @@ def fold(grid: Grid, direction: str, axis: int):
if direction == "y":
for y in range(axis + 1, grid.maxY + 1):
targetY = axis - (y - axis)
for x in grid.rangeX():
grid.add(Coordinate(x, targetY), grid.get(Coordinate(x, y)))
for x in grid.getActiveCells(y=y):
grid.add(Coordinate(x.x, targetY), grid.get(x))
grid.set(x, 0)
grid.maxY = axis - 1
elif direction == "x":
for x in range(axis + 1, grid.maxX + 1):
targetX = axis - (x - axis)
for y in grid.rangeY():
grid.add(Coordinate(targetX, y), grid.get(Coordinate(x, y)))
for y in grid.getActiveCells(x=x):
grid.add(Coordinate(targetX, y.y), grid.get(y))
grid.set(y, 0)
grid.maxX = axis - 1
@ -39,12 +41,8 @@ class Day(AOCDay):
fold_1 = folds[0]
direction, axis = fold_1.split()[-1].split("=")
fold(grid, direction, int(axis))
onCount = 0
for x in grid.rangeX():
for y in grid.rangeY():
onCount += grid.get(Coordinate(x, y)) > 0
return onCount
return len(grid.getActiveCells())
def part2(self) -> Any:
coords, folds = self.getMultiLineInputAsArray()