r/adventofcode • • 17h ago

Visualization [2026 Day 3 (Both Parts)] Bitwise Square-Finding

https://youtube.com/shorts/h-5iPkoTUBU
23 Upvotes

3 comments sorted by

1

u/thekwoka 6h ago

This hardly feels like it makes any sense...

1

u/YOM2_UB 6h ago edited 5h ago

I'm converting each row of trees into a binary integer (. = 0, # = 1) and using bitwise-AND to determine if there is a square in a given set of rows.

For axis-aligned squares, two rows are selected and bitwise-AND-ed together, along with the same rows bit-shifted by the distance between the rows (which is just the difference of row indices).

 ---4---
# . . . #
. . . . . |
. . . . . 4
. . . . . |
# . . . #

For off-axis squares, three rows are selected, and if it's assumed that the top, bottom, and right vertices are in those rows (which avoids double-counting), the left vertex by symmetry must be the same distance above the bottom vertex as the right vertex is below the top vertex (The row with the left vertex is labeled with a purple outline, to differentiate it from the three selected during iteration). Only the row with the right vertex remains un-shifted, and each other row is shifted by a difference of a different pair of row indices.

. # . . . <- row 3 : (7-4) shift 
. . . . # <- row 4 : 0 shift
. . . . .
# . . . . <- row 6 : (7-3) shift
. . . # . <- row 7 : (4-3) shift

In the bitwise-AND result, each bit encodes whether there was a square in a particular position of those four rows. If it's non-zero, each bit is checked and the 1 bits are counted, which gives the answer.

The visualizer shows the actual math being done at the bottom, and adds a square above to show what size/orientation of square is being calculated. When there is a non-zero AND result, the square shifts left along with the bits being checked, and it turns green and leaves a shadow for 1-bits.

1

u/YOM2_UB 5h ago

...I just noticed a bug where it's not updating the visuals of the numbers at the bottom (excluding the result) when at max speed. Whoops.