The puzzle
The input is a forest map. Each # marks a tree and each . marks empty ground. A square counts when a tree stands at each of its four corners. Cells along the edges or inside the square can contain either symbol.
- Part 1 counts squares whose sides follow the grid’s rows and columns.
- Part 2 counts squares at any angle, including the aligned squares from Part 1.
Part 1. Start with four corner checks
I started by trying each side length and each top-left corner that could fit it. At each position, I read the four cells and counted one square if all four held trees. That gave me a simple reference for the packed version.
- Baseline
- 0.8005ms
Part 1 baseline JavaScript
function scanAligned(input) {
const rows = input.trim().split(/\r\n?|\n/);
const width = rows[0].length;
const height = rows.length;
const grid = new Uint8Array(width * height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) grid[y * width + x] = Number(rows[y][x] === "#");
}
let count = 0;
for (let side = 1; side < Math.min(width, height); side++) {
for (let y = 0; y + side < height; y++) {
const top = y * width;
const bottom = (y + side) * width;
for (let x = 0; x + side < width; x++) {
if (grid[top + x] && grid[top + x + side] && grid[bottom + x] && grid[bottom + x + side]) count++;
}
}
}
return [count];
}In the example forest, rows 0 and 1 both have trees in columns 1 and 2. The rows are one cell apart and so are the columns. Those four trees form a square of side one.
Check many corners with one shift
| Column | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Row 0 | 0 | 1 | 1 | 0 | 0 |
| Row 1 | 0 | 1 | 1 | 0 | 0 |
| Both | 0 | 1 | 1 | 0 | 0 |
| Both ≫ 1 | 1 | 1 | 0 | 0 | 0 |
| Left corners | 0 | 1 | 0 | 0 | 0 |
For a fixed side length and top row, the scalar scan rereads the same two rows for every starting column. I packed those rows into bit masks so I could test columns together. The first AND keeps columns with a tree in both rows. To find neighboring marks, move a copy of those bits one column left and AND again. At column 1, the original bit and the bit shifted from column 2 are both set. That surviving bit gives the top-left corner of the square.
For a square of side d, use rows d cells apart and shift by d. Pack row y into the integer . Bit x stores , one for a tree and zero for empty ground. The two masks below are C for “Both” and L for “Left corners.” Bit zero is at the left in the diagram, so a numerical right shift moves the marks toward the smaller column numbers.
Every aligned square has a unique top row, side length, and left column. Sum the population counts of the corner masks over all valid side lengths and top rows. In an H by W grid, d runs from 1 through the smaller dimension minus one, and y from 0 through H − d − 1.
Shift across word boundaries
A BigInt per row expresses the proof directly. Given two packed rows and their separation, this yields the mask of left corners.
const common = topRow & bottomRow;
const corners = common & (common >> BigInt(side));
The browser implementation packs the same bits into Uint32Array words. A shift of d skips q whole words and moves r bits within a word. If r is positive, the high bits come from the adjacent word. Treat missing words at the end of a row as zero. The zero-remainder case uses the source word directly, since JavaScript reduces ordinary Number shift distances modulo 32.
OR the two pieces to form the shifted word and keep its low 32 bits. JavaScript’s unsigned >>> provides the zero-filled right shift. The solver counts the resulting bits by adding adjacent bit fields into wider fields, then adding the byte counts with a multiply. This makes population count a fixed amount of work per surviving word. Henry S. Warren Jr., Hacker’s Delight, chapter 5.
Inside the word loop, top and bottom are offsets into the packed row array, and word is the index of the output word inside a row.
const common = masks[top + word] & masks[bottom + word];
if (!common) continue;
const source = word + wordOffset;
let shifted = masks[top + source] & masks[bottom + source];
if (bitOffset) {
shifted >>>= bitOffset;
// Zero-fill at the edge of the row, including across the last word.
if (source + 1 < words) {
const high = masks[top + source + 1] & masks[bottom + source + 1];
shifted |= high << (32 - bitOffset);
}
}
aligned += populationCount(common & shifted);- Split the shiftA shift of 35 skips one word and moves three bits further.
- Take 29 bitsSource word 1 contributes its bits 3–31 to bits 0–28 of the result.
- Carry 3 bitsSource word 2 contributes its bits 0–2 to bits 29–31 of the result.
The scalar search tries W − d starting columns for each row pair. Packed words reduce that to at most word checks after the initial grid pass. The packed form also skips an entire word whenever the two rows have no common trees there.
- Before
- 0.8005ms
- After
- 0.0667ms
- Speedup
- 12.0×
Detour. Put the whole forest in one integer
The row loop can disappear too. Concatenate the binary rows into one integer B, with the first character at the most significant end. For side length d, shifting by dW aligns rows everywhere at once. AND to get a mask of vertical edges, then shift by d and AND again to get pairs of edges. A surviving bit marks the bottom-right corner in this ordering.
A flat horizontal shift can bring a bit in from the previous row. To rule that out, put a 1 in the least significant bit of every row to make G. Shifting that pattern by W − d and subtracting the original produces W − d consecutive 1s in each row. Those low bits allow a bottom-right corner only where there is room for d columns to its left.
| Side 1 | Row 0 | Row 1 | Row 2 |
|---|---|---|---|
| Vertical pairs | 0000 | 1001 | 1001 |
| Shift right one | 0000 | 0100 | 1100 |
| Intersect | 0000 | 0000 | 1000 |
| Legal anchors | 0111 | 0111 | 0111 |
| Corners after mask | 0000 | 0000 | 0000 |
#..# contain no side-one square. The flat shift lets the last column of row 1 spill into the first column of row 2. The mask clears that false corner.The Python loop visits each side length once. Each shift, AND, and population count still processes the integer’s internal words. Python does those passes inside its integer implementation, which saves dispatching a Python loop for every row pair. Python’s integer documentation.
def whole_board(text):
rows = text.split()
width, height = len(rows[0]), len(rows)
bits = str.maketrans(".#", "01")
board = int("".join(rows).translate(bits), 2)
row_starts = int(("0" * (width - 1) + "1") * height, 2)
total = 0
for side in range(1, min(width, height)):
common = board & (board >> (side * width))
valid = (row_starts << (width - side)) - row_starts
total += (common & (common >> side) & valid).bit_count()
return total
JavaScript mirrors the mask arithmetic with BigInt. The benchmark implements the population count by folding adjacent bit fields into lane counts. Once the radix q of a lane is big enough that q − 1 exceeds the entire board’s cell count, take the packed integer modulo q − 1. Each radix power has remainder one, so the remainder is the sum of the lane counts. The bound ensures the sum itself fits without wrapping. ECMAScript’s BigInt specification.
const common = board & (board >> BigInt(side * width));
const valid = (rowStarts << BigInt(width - side)) - rowStarts;
let corners = common & (common >> BigInt(side)) & valid;
if (!corners) continue;
for (const [shift, lowLanes] of folds) {
corners = (corners & lowLanes) + ((corners >> shift) & lowLanes);
}
total += Number(corners % modulus);
The single integer removed an explicit loop over row pairs. It still had to shift and reduce a large integer for each side length. It took 0.693 ms against 0.0667 ms for packed words on Bob’s grid. I kept the packed rows and looked for ways to visit fewer positions.
Start from occupied pairs in sparse rows
The top edge also determines the side length. If two trees on row y are at columns x and x + s, test those two bits on row y + s. Each aligned square has one top edge, so these pairs cover every square exactly once. The implementation walks set bits to recover the two top columns and uses the same packed rows for the bottom-corner tests. Van Kreveld and de Berg, Finding Squares and Rectangles in Sets of Points.
Here ky counts trees on row y. The bound includes edges whose side would put the bottom row out of bounds. The solver compares that bound with the number of possible anchor positions in the packed search. Sparse rows can offer fewer top-edge pairs than the packed loop would visit words.
- Before
- 0.0667ms
- After
- 0.0297ms
- Speedup
- 2.25×
Part 2. Find tilted squares
The same forest contains one tilted square. Start at the tree A in column 2, row 1. The edge to tree B goes two columns right and one row down. Turn that edge 90 degrees clockwise to get a move of one column left and two rows down. Make that move from both A and B to find the other corners.
Use the turned edge at both A and B. It lands at D (1, 3) and C (3, 4). Both positions have trees, so the square counts.
For any tilted square, choose the topmost tree A and follow its edge toward the right. Call that offset , with a columns right and b rows down. Both are positive. The clockwise turn gives the second offset v, which we add to both endpoints of the first edge.
The dot product is zero and the two lengths are equal. Translating the endpoints by the rotated edge completes a square. Picking the topmost corner and its unique rightward edge makes the representation unique. If the top edge stays on one row, the square belongs to the aligned count already computed. Gilbert Strang, Mathematical Methods for Engineers, on plane rotations.
I started by walking the list of occupied tree pairs for possible edges. For each pair that could fit a square, I checked the two corners implied by the quarter-turn.
- Baseline
- 1.108ms
Tilted-square baseline JavaScript
Pass in the grid as an array of rows. This function counts only the tilted squares, which are then added to the aligned count.
function countTilted(rows) {
const width = rows[0].length;
const height = rows.length;
const grid = new Uint8Array(width * height);
const columns = [];
const lines = [];
const rowEnds = new Uint32Array(height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
if (rows[y][x] !== "#") continue;
grid[y * width + x] = 1;
columns.push(x);
lines.push(y);
}
rowEnds[y] = columns.length;
}
let tilted = 0;
for (let a = 0; a < columns.length; a++) {
const x = columns[a];
const y = lines[a];
for (let b = rowEnds[y]; b < columns.length; b++) {
const dy = lines[b] - y;
// The rotated side goes dy to the left and at least one row down.
if (dy > x || y + dy + 1 >= height) break;
const dx = columns[b] - x;
if (dx <= 0 || y + dy + dx >= height) continue;
if (grid[(y + dx) * width + x - dy] &&
grid[(y + dy + dx) * width + columns[b] - dy]) {
tilted++;
}
}
}
return tilted;
}Start at the first possible tree
Before trying pairs of trees, rule out any second corner B that would put the rest of the square outside the forest. With the anchor at (2, 1), the Search area step shades columns 3 and 4 on rows 2 and 3. Only one of those positions contains a tree, so the solver needs to check one pair for that anchor.
For an anchor at (x, y), a candidate B is on row y + b. The turned edge travels b cells left, so b cannot exceed x. The lowest corner lands on row y + a + b, so a must be less than H − y − b. These bounds tell us which columns to search on each row.
I stored the occupied columns consecutively in row order. An index at each grid position points to the first tree at or beyond that position in its row, or the end of that row’s list. Two indexed offsets delimit the eligible trees directly.
- Before
- 1.108ms
- After
- 0.645ms
- Speedup
- 1.72×
Add the two corner checks without a branch
The indexed version still calculated two full offsets for each candidate. For fixed A and b, each remaining pair shares the same index bases for D and C. I moved those calculations outside the inner loop. The two lookups return 0 or 1, so their bitwise AND is the contribution to the count.
for (let dy = 1; dy <= maxDy; dy++) {
const otherRow = (y + dy) * stride;
const from = offsets[otherRow + x + 1];
const to = offsets[otherRow + Math.min(width, x + height - y - dy)];
const nearBase = (y - x) * width + x - dy;
const farBase = nearBase + dy * width - x;
for (let j = from; j < to; j++) {
const right = columns[j];
const row = right * width;
tilted += grid[nearBase + row] & grid[farBase + row + right];
}
}- Before
- 0.645ms
- After
- 0.356ms
- Speedup
- 1.81×
Batch all anchors for a fixed tilt
The same tilt can be tested with row masks. With fixed a, b, and top row y, align all four row masks to column x at A. Here shifts right by k when positive and left by its magnitude when negative.
Could packing help the tilted search too? This batches horizontal positions for each pair of offsets. On Bob’s sparse grid, it took 3.74 ms against 0.356 ms for indexed pairs. The result flipped when I filled a generated 141 by 141 grid to 99%. On that grid, the earlier tree-pair solver spent most of its time visiting edges between occupied cells.
In the packed layout, columns run from low to high bits and every row starts on a word boundary. Let S be the padded row stride in bits. The four corners sit at offsets 0, u, v, and u + v from the anchor, where u = bS + a and v = aS − b. Both offsets are positive because both edges go down. Each shifted word can therefore be assembled from at most two adjacent words.
We only visit rows above H − a − b and mask the columns to the interval from b through W − 1 − a. Inside that rectangle, every shifted bit refers to a corner in the intended row. In the inner loop, an empty intersection lets us skip the remaining corners.
anchors &= shiftedWord(board, i + uWords, u & 31);
if (!anchors) continue;
anchors &= shiftedWord(board, i + vWords, v & 31);
if (!anchors) continue;
anchors &= shiftedWord(board, i + bothWords, (u + v) & 31);
total += populationCount(anchors);- Before
- 57.8ms
- After
- 5.76ms
- Speedup
- 10.0×
Count a full forest without searching
A square with edge (a, b) spans s = a + b cells along each axis, measured from one extreme coordinate to the other. Its bounding box has (W − s)(H − s) placements. For each span there are s − 1 tilted shapes, one for each choice of b from 1 to s − 1. Adding the aligned shape with b = 0 gives s shapes per span.
The aligned count sums (N − s)² over the same spans. Subtracting it leaves 6,786,800 tilted squares at N = 96. Both search implementations agree with that independent count. The solver uses the sums directly when every cell contains a tree. Duane W. DeTemple, Counting Squares to Sum Squares.
Correct the count using only the holes
The almost-full grid raised a different question. Could I count the squares that were lost to holes? I started with the full rectangle’s count. For each hole, subtract all squares with that corner. Rotate the coordinate system through the four possible roles for that corner. In one orientation a tilted square’s offsets satisfy a ≥ 1, 1 ≤ b ≤ L, a ≤ R, and a + b ≤ D, where L, R, and D are the available cells left, right, and down.
The sum starts with a flat segment of R choices per row and then falls by one per row. Compute both segments with arithmetic-series formulas. Aligned squares use b = 0, which gives min(R, D) choices per orientation.
A square with several holes gets subtracted several times. To correct it, generate the at most three squares implied by each hole pair. The pair can form an edge with a square on either side or a diagonal with a unique completion. For each of those squares, add one back only if the earlier hole of the pair is also the earliest hole of the square in row-major order.
| Holes in a square | Corrections | Net count |
|---|---|---|
| None | None | 1 |
| A, B, C in row order | Subtract A, B, C. Add back AB and AC. | 1 − 3 + 2 = 0 |
After parsing and summing the full-rectangle counts, the work is O(h²) for h holes. The browser caps this path at 512 holes and requires the full tilted count to be at least 128h². For the other forests it uses the packed tilt search at 60% occupancy or more when both dimensions reach 24. These cutoffs trade the cost of each loop against the amount of work it skips.
- Before
- 5.76ms
- After
- 0.649ms
- Speedup
- 8.9×
Pack 64 columns into a Wasm word
The JavaScript version used 32-bit words because its ordinary bitwise operators work on that width. In Rust, a u64 buys twice as many columns per word. The compiler emits Wasm’s i64.popcnt for count_ones(), so the browser can count every surviving corner bit in one instruction. WebAssembly Core Specification, numeric instructions.
The sparse solver still checks tree pairs. It keeps the validated map as a contiguous array of ASCII bytes. Since # has its low bit set and . clears it, the two corner reads can contribute directly to the sum.
let dx = right - x;
let down = dx * width;
tilted += u64::from(grid[near + down] & grid[far + down + dx] & 1);
For the nearly full case, the port can check the two remaining corners directly in the grid as it assigns duplicate corrections to their earliest hole. The choice among sparse pairs, packed words, and hole corrections still depends on the shape of the forest.
- Before
- 0.5219ms
- After
- 0.3938ms
- Speedup
- 1.33×
Benchmarks
| Workload | Adaptive JavaScript | Rust/Wasm |
|---|---|---|
| Bob’s input, fresh worker | 10.7 ms | 7.4 ms |
| Bob’s input, warm solve | 0.522 ms | 0.394 ms |
| Generated 96 by 96 forest at 90% occupancy, warm solve | 1.975 ms | 0.944 ms |
| Generated 141 by 141 forest at 99% occupancy, warm solve | 0.681 ms | 0.161 ms |
The browser comparisons use Chromium 147 on a Threadripper 9970X, with Rust 1.100.0 targeting wasm32-unknown-unknown. Each figure is the median of nine measurements. Warm measurements batch complete solves, including input encoding when needed. Fresh measurements include worker startup, loading the solver on localhost, and receiving both answers. The full-solve baseline for the final recap is the scalar search over in-bounds offsets.
The earlier JavaScript milestones and the crossover chart below use Bun v1.4.5. For the Part 1 chain, each variant warmed up in its own Bun process. When I ran all variants in one process, the sparse version took 0.093 ms while the packed scan took 0.068 ms. The sparse speedup was sensitive to the benchmark setup.
Where packed words overtake tree pairs
On the scattered 96 by 96 grids, the indexed pair loop leads through 25% occupancy. Packed words take the lead at 50%, with a wider margin at 90%. The pair search does more work as the number of eligible edges grows. The packed search visits the same words for each grid size, and the placement of trees determines how often it can skip later intersections.
| Trees | Tree pairs faster | Packed words faster |
|---|---|---|
| 8% scattered | 9.69× | |
| 16% scattered | 6.64× | |
| 25% scattered | 3.38× | |
| 50% scattered | 1.24× | |
| 90% scattered | 3.99× | |
| 25% block | 1.50× | |
| 25% lattice | 1.41× |
A block and a lattice can favor different searches at the same occupancy. The strategy switch uses occupancy as a cheap estimate.
- Start
- 3.275ms
- Finish
- 0.394ms
- Speedup
- 8.32×
Run the solver
Paste a rectangular grid using # for trees and . for empty cells. Your input stays in this browser.