Twelve Days · day 9 · both parts
Day 9: Movie Theater
Part 1 is a loop over pairs. Part 2 adds a polygon that is a hundred thousand tiles across, and the interesting part is shrinking it to the few hundred rows and columns that actually matter.
The puzzle, in my words
A list of red tiles on a huge floor of square tiles, one x,y per line. Take
two red tiles as opposite corners of a rectangle and count the tiles it
covers, edges included. What’s the biggest rectangle you can make?
The example has eight red tiles. The rectangle from 2,5 to 9,7 is 8 tiles
wide and 3 tall, so 24; the biggest is 50, from 2,5 to 11,1.
Part 1: every pair of corners
Step 1: the first version
Read the tiles, then try every pair, with the second index starting after the first so each pair comes up once:
def part1(text: str) -> int:
tiles = []
for line in text.split():
x, y = line.split(",")
tiles.append((int(x), int(y)))
best = 0
for i in range(len(tiles)):
for j in range(i + 1, len(tiles)):
(x1, y1), (x2, y2) = tiles[i], tiles[j]
area = (abs(x1 - x2) + 1) * (abs(y1 - y2) + 1)
best = max(best, area)
return best
The + 1 is because the area counts tiles, not the distance between their
centres: from column 2 to column 9 is 8 tiles. Real inputs reportedly have
about 500 red tiles, so about 125,000 pairs. On a generated input of that
size it takes about 12 ms.
Step 2: say it with combinations
itertools.combinations(tiles, 2) yields each unordered pair once, which is
what the two index loops were doing, and one max over a generator replaces
the running best:
from itertools import combinations
def tiles(text: str) -> list[tuple[int, int]]:
return [tuple(map(int, line.split(","))) for line in text.split()]
def part1(text: str) -> int:
return max(
(abs(x1 - x2) + 1) * (abs(y1 - y2) + 1)
for (x1, y1), (x2, y2) in combinations(tiles(text), 2)
)
About the same speed, 10 ms against 12. That’s all part 1 needs.
Part 2: only red and green
Now the order of the list matters. Each red tile is joined to the next by a
straight line of green tiles, and the last one back to the first, which
closes a loop. Every tile inside the loop is green too. The rectangle still
has red corners, but it may only cover red or green tiles. On the example the
best is 24, from 2,3 to 9,5.
In other words, the red tiles are the corners of an orthogonal polygon, and the rectangle has to fit inside it, touching the edge being allowed.
Step 1: paint the floor
The direct way: work out which tiles are green, then check every tile of every rectangle. The loop’s own tiles are easy. For the inside, go row by row and look at the vertical edges the row crosses; between the first and second crossing you’re inside, between the second and third outside, and so on.
from itertools import combinations, product
def loop(tiles):
return list(zip(tiles, tiles[1:] + tiles[:1]))
def part2(text: str) -> int:
red = tiles(text)
edges = loop(red)
green = set()
for (x1, y1), (x2, y2) in edges:
for x in range(min(x1, x2), max(x1, x2) + 1):
for y in range(min(y1, y2), max(y1, y2) + 1):
green.add((x, y))
verticals = [(x1, min(y1, y2), max(y1, y2)) for (x1, y1), (x2, y2) in edges if x1 == x2]
ys = [y for _, y in red]
for y in range(min(ys), max(ys) + 1):
cuts = sorted(x for x, lo, hi in verticals if lo <= y < hi)
for a, b in zip(cuts[::2], cuts[1::2]):
green.update((x, y) for x in range(a, b + 1))
best = 0
for (x1, y1), (x2, y2) in combinations(red, 2):
xs = range(min(x1, x2), max(x1, x2) + 1)
rows = range(min(y1, y2), max(y1, y2) + 1)
if all(t in green for t in product(xs, rows)):
best = max(best, len(xs) * len(rows))
return best
The one subtle line is lo <= y < hi. A row that runs along a horizontal
edge meets two corners at once. Counting an edge only on the rows from its
top end down to just above its bottom end means a bump in the outline
(both edges going the same way) counts twice or not at all, and a step
(one up, one down) counts once, which is what the inside/outside switch needs.
This gets 24 on the example. But real floors are reported to be about 100,000 tiles on a side: ten billion tiles to paint. It can’t run there.
Step 2: squeeze the floor
Red tiles come in pairs that share a column (the two ends of a vertical edge), so 500 of them use at most 250 distinct columns, and likewise at most 250 rows; the generated input below has 245 and 247. Every edge of the loop lies on one of those columns or rows, so in the stretch between two neighbouring ones nothing changes: it’s all inside or all outside. So give each of those columns its own slot, give each stretch between two of them one slot, and add a border slot on each side. That’s coordinate compression: a floor of about 500 by 500 slots instead of 100,000 by 100,000.
from itertools import pairwise
def squeeze(values):
vals = sorted(set(values))
slot = {v: 2 * k + 1 for k, v in enumerate(vals)}
width = [1]
for a, b in pairwise(vals):
width += [1, b - a - 1]
width += [1, 1]
return slot, width
itertools.pairwise (Python 3.10+) yields each value with the next one.
slot says where each column (or row) lands; width says how many tiles
each slot stands for. A stretch between columns 7 and 9 holds one tile; one
between 9 and 10 would hold none, but the slot stays anyway, and that is on
purpose. Picture two edges on neighbouring columns, a channel with no tiles
in it, leading into an empty room that is outside the loop. Without the
empty slot, a flood fill could never get through the channel, and the room
would count as inside. Write-ups report that real inputs never put two edges
right beside each other, so this may not matter there, but the code doesn’t
rely on it, and the tests include such a room.
On the squeezed floor, mark the loop, flood the outside from a corner, and keep the slots that are outside and actually hold tiles:
def outside(red):
sx, wx = squeeze([x for x, _ in red])
sy, wy = squeeze([y for _, y in red])
cols, rows = len(wx), len(wy)
wall = [[False] * cols for _ in range(rows)]
for (x1, y1), (x2, y2) in loop(red):
a, b = sorted((sx[x1], sx[x2]))
c, d = sorted((sy[y1], sy[y2]))
for r in range(c, d + 1):
for col in range(a, b + 1):
wall[r][col] = True
out = [[False] * cols for _ in range(rows)]
out[0][0] = True
todo = [(0, 0)]
while todo:
r, c = todo.pop()
for rr, cc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= rr < rows and 0 <= cc < cols and not wall[rr][cc] and not out[rr][cc]:
out[rr][cc] = True
todo.append((rr, cc))
bad = [[out[r][c] and wx[c] > 0 and wy[r] > 0 for c in range(cols)] for r in range(rows)]
return sx, sy, bad
def area(a, b):
return (abs(a[0] - b[0]) + 1) * (abs(a[1] - b[1]) + 1)
def part2(text: str) -> int:
red = tiles(text)
sx, sy, bad = outside(red)
for a, b in sorted(combinations(red, 2), key=lambda p: area(*p), reverse=True):
c1, c2 = sorted((sx[a[0]], sx[b[0]]))
r1, r2 = sorted((sy[a[1]], sy[b[1]]))
if not any(any(bad[r][c1 : c2 + 1]) for r in range(r1, r2 + 1)):
return area(a, b)
return 0
The areas still come from the real coordinates; the slots only answer “is any of this outside?”. Trying pairs from the largest down means the first one that passes is the answer, which is what the clip shows. The list is a stack, so this flood fill is depth-first; the order doesn’t matter, only which slots it reaches.
On a generated input shaped like the real ones (494 red tiles, coordinates up to 100,000, a staircase round a circle with a thin cut nearly through it, as write-ups describe them) this takes about 1.2 s. The slow part is the check: a big rectangle that fails can mean scanning a few hundred rows of slots first, and the largest rectangles are the ones that fail.
Step 3: a summed-area table
To ask “is anything in this rectangle outside?” in constant time, add up the
bad slots once: total[r][c] is the number of bad slots above and to the
left of slot (r, c). Then the count inside any rectangle is four lookups,
whatever its size:
def part2(text: str) -> int:
red = tiles(text)
sx, sy, bad = outside(red)
cols = len(bad[0])
total = [[0] * (cols + 1)]
for row in bad:
run, line = 0, [0]
for c, b in enumerate(row):
run += b
line.append(total[-1][c + 1] + run)
total.append(line)
best = 0
for (x1, y1), (x2, y2) in combinations(red, 2):
area = (abs(x1 - x2) + 1) * (abs(y1 - y2) + 1)
if area <= best:
continue
c1, c2 = sorted((sx[x1], sx[x2]))
r1, r2 = sorted((sy[y1], sy[y2]))
if total[r2 + 1][c2 + 1] - total[r1][c2 + 1] - total[r2 + 1][c1] + total[r1][c1] == 0:
best = area
return best
run += b works because True is 1. The table has an extra row and column
of zeros at the top and left, so the lookups never need a special case for
a rectangle on the border.
Now every pair costs the same, and pairs that can’t beat the best so far are skipped before any lookup, so there’s no need to sort. On the same generated input this takes about 0.1 s instead of 1.2 s, and about half of that is building the squeezed floor.
The tests check all three steps against a brute force with no grid at all, which asks of every tile in every rectangle whether it’s on the loop or inside it, by counting the vertical edges to its right. All three steps agree with it on 400 random small orthogonal loops (random blobs of cells, outlined, with the axes stretched by gaps of 1 to 3), and on the channel-and-room loop described above.
All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own.