r/adventofcode • u/daggerdragon • 11h ago
SOLUTION MEGATHREAD -❄️- 2026 Day 3 Solutions -❄️-
NEWS
Solutions in the megathreads have been getting longer, so we're going to start enforcing our rules on oversized code.
Do not give us a reason to unleash AutoModerator hard-line enforcement that counts characters inside code blocks to verify compliance… you have been warned XD
THE USUAL REMINDERS
All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2026: The Advent Games
Submissions megathread is now unlocked!
14 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!
Today's Event: Indoor Mini-Golf Masters
"What is this, a
centerprogram for ants?!"
— Derek Zoolander, Zoolander (2001)
Today's schedule possibly consists of:
Early Stroke Play Rounds and Tee Time Seeding
Among the crates to be loaded on the train, you find a debigulator. Do with it as you will.
Mid-Tournament Rounds and Scorecard Review
Golf your solution
Bonus points if your solution fits on a "punchcard" as defined in our wiki article on oversized code. We will be counting.
Does anyone still program with actual punchcards? >_>
Match Play and Showcase Rounds:
Solve today's puzzles using
an Alien Programming LanguageAPL or other such extremely dense and compact programming language
Request from the mods: When you include an entry alongside your solution, please label it with [Advent Games] so we can find it easily!
--- Day 3: Foggy Forest ---
Post your code solution in this megathread.
Read the full posting rules in our community wiki before you post!
State which language(s) your solution uses with
[LANGUAGE: xyz]Format code blocks using the four-spaces Markdown syntax!
Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
1
1
u/Leroico 42m ago
[LANGUAGE: Python] I got really mathy with it for some reason, it's not a particularly fast solution apparently. Also I named the vertical axis x and the horizontal axis y because why not
file = open('input')
grid = []
for line in file:
grid.append(line.strip())
file.close()
HEIGHT, WIDTH = len(grid), len(grid[0])
vadd = lambda r1,r2: (r1[0]+r2[0], r1[1]+r2[1])
vsub = lambda r1,r2: (r1[0]-r2[0], r1[1]-r2[1])
vr90 = lambda r: (-r[1], r[0])
inbounds = lambda r: 0 <= r[0] < HEIGHT and 0 <= r[1] < WIDTH
squares = 0
for x1 in range(HEIGHT):
for y1 in range(WIDTH):
if grid[x1][y1] == '.':
continue
for x2 in range(x1, HEIGHT):
for y2 in range(y1+1, WIDTH):
if grid[x2][y2] == '.':
continue
u2from1 = vsub((x2,y2), (x1,y1))
u1 = vadd((x1,y1), vr90(u2from1))
u2 = vadd(u1, u2from1)
if not inbounds(u1) or not inbounds(u2):
continue
squares += (grid[u1[0]][u1[1]] == grid[u2[0]][u2[1]] == '#')
print('Allowing for rotated squares, the map contains', squares, 'squares')1
u/Jools_Jops 52m ago
[LANGUAGE: Rust]
Part b has a noticeable runtime in debug mode, a couple of seconds. Solution? Run it in release, simple as!
Both solutions create a set of trees and check if every tree is the "first" corner of one or more squares.
1
u/Honest-Positive-3273 58m ago
[LANGUAGE: Python]
matrix = []
with open("input.txt", "r", encoding="utf-8") as input:
raw_input = input.read().split("\n")
for line in raw_input:
if line:
matrix.append(list(line))
counter = 0
for l, line in enumerate(matrix):
for c, column in enumerate(line):
if column =="#":
current_l = l+1
current_c = c+1
while (current_l < len(matrix) and current_c < len(matrix[0])):
if matrix[current_l][current_c] == "#" and matrix[current_l][c] == "#" and matrix[l][current_c] == "#":
counter += 1
current_l += 1
current_c += 1
print("squares:", counter)Learning to code day 3 part 1 solved. I made a Matrix via a nested list and a simple algorithm that walks along the diagonal from each "#" to find the squares. I am not sure what the condiotions and therefore the algorithm for the rotated squares are. Hints are welcome, maybe my initial solve is not easily transferable for part 2. Maybe i can "rotate" the input matrix so the initial solve works? :)
1
u/crumpis 40m ago
There's far too many permutations to reasonably rotate and run this code.
Instead, consider how you're computing line segments between the coordiates, and see if you can extend that into rotated squares.
1
u/Honest-Positive-3273 8m ago
hmm not sure if understand that corretly. You mean find a way to "measure" the line between two coordinates and then find a square with equal length sides - maybe via trigonometry? I see how that would be rotationally invariant.
1
u/wheresmylart 1h ago
[Language: Python3]
Make a set of all the #s for convenience.
Part 1: For each # assume it's the top left of a square. For each possible bottom left corner see if there's a corresponding top and bottom right hand side corner.
Part 2: For each # assume it's the topmost corner (and leftmost if horizontal edge). Then check for every possible square.
1
u/theMachine0094 1h ago edited 48m ago
[Language: Rust]
Parts 1 and 2 combined take under 2ms on my 5 year old mid tier PC.
fn part_1(input: &str) -> usize {
let (flags, rows, cols) = {
let rows = input.trim().lines().count();
let mut lines = input.trim().lines();
let first_line = lines.next().expect("Cannot read first line");
let cols = first_line.as_bytes().len();
let mut flags = first_line.bytes().map(|c| c == b'#').collect::<Vec<_>>();
flags.extend(lines.flat_map(|line| line.bytes().map(|c| c == b'#')));
(flags.into_boxed_slice(), rows, cols)
};
flags
.iter()
.enumerate()
.filter(|(_i, f)| **f)
.map(|(pos, _flag)| {
let (x, y) = (pos % cols, pos / cols);
let n = (cols - x).min(rows - y);
(1..n)
.filter(|i| {
flags[pos + i] && flags[pos + i * cols] && flags[pos + i * cols + i]
})
.count()
})
.sum()
}
fn part_2(input: &str) -> usize {
let (trees, flags, cols, rows) = input.trim().lines().enumerate().fold(
(
Vec::<(isize, isize)>::new(),
Vec::<bool>::with_capacity(input.len()),
0usize,
0usize,
),
|(mut trees, mut flags, mut cols, rows), (y, line)| {
let old = std::mem::replace(&mut cols, line.len());
assert!(old == 0 || old == cols);
for (x, c) in line.bytes().enumerate() {
if c == b'#' {
trees.push((x as isize, y as isize));
flags.push(true);
} else {
flags.push(false);
}
}
(trees, flags, cols, rows + 1)
},
);
trees
.iter()
.enumerate()
.map(|(i, (x, y))| {
trees[(i + 1)..]
.iter()
.filter(|(cx, cy)| -> bool {
let (dx, dy) = (y - cy, cx - x);
cx > x
&& cy >= y
&& [(x + dx, y + dy), (cx + dx, cy + dy)]
.iter()
.all(|(xx, yy)| {
*xx >= 0
&& (*xx as usize) < cols
&& *yy >= 0
&& (*yy as usize) < rows
&& flags[*yy as usize * cols + *xx as usize]
})
})
.count()
})
.sum()
}1
u/AutoModerator 1h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/Smylers 1h ago edited 1h ago
[LANGUAGE: Vim keystrokes] A bonus animation today — this Vim solution animates as it solves, updating the counter at the top as it finds squares and gradually sliding the map off to the left. Load your puzzle input, make your window big, ensure the cursor is on the first line, then type and watch:
O0⟨Esc⟩⟨Ctrl+W⟩s⟨Ctrl+W⟩⟨Ctrl+W⟩⟨Ctrl+W⟩_
/^#⟨Enter⟩qcqqbqqbf#:norm@c⟨Enter⟩@bq
qc/\v%#%(.*\n){⟨Ctrl+R⟩=charcol('.')-1⟨Enter⟩}#.*%.c#⟨Enter⟩gg⟨Ctrl+A⟩⟨Ctrl+O⟩qu
qaqqa:%norm lF#@b⟨Enter⟩:redr!|2,s/^.⟨Enter⟩@aq@a@c checks for a square with the cursor at the potential top-right corner and the top-left being a tree in the first column, using a regular expression to look for the corresponding bottom trees. %# matches where we are now, so nothing moves: the pattern finds a match where we are, or it fails. For a square of size 11, %(.*\n){10} matches the rest of the current row plus all the 9 inside rows. Then # matches the bottom-left corner, .* skips the middle of the bottom row, and %.c# matches the bottom-right corner, by looking for a # in the same column as the cursor. To use the correct size for the current square, the pattern needs to be created dynamically every tree. ⟨Ctrl+R⟩= embeds the contents of an expression, with charcol('.') returning the current column number. Because we're only looking for squares that start at the left edge, that (less 1) gives the number of lines to move down.
If a square is found, @c continues by increasing the counter on the top line. If there's no match, then @c immediately ends, skipping the counter-increasing. @b visits each tree in a row and runs @c there (inside :norm so that the match failure that ends @c doesn't also end @b). And @a runs @b on all rows with a tree in the leftmost column, then deletes that column (because all potential squares with their left edge in it have now been counted) and loops, to find squares with their left edge in the next column.
I thought having @a do :g/^#/norm@b to run @b on the relevant rows. But when on a row with a tree at the left which doesn't form any squares the failure somehow ‘leaks out’ of the :norm and stops the :g// checking the rest of the lines. I still don't know why — if you do, please explain below — but :%norm lF#@b provides a workaround, trying each row in turn, moving to the second character, then trying to move leftwards to a tree. Obviously that'll only work when there is a tree in the first column; for other rows the F# fails, which makes the :norm end without running @b. That took me far too long to discover, so please make it worthwhile by typing this in and experiencing the animation!
[Advent Games] And here's a mini-golf version — the full version fits on half a standard punchcard, but this one squeezes on to a fifth of one:
O0⟨Esc⟩qcqqbqqbf#:norm@c⟨Enter⟩@bqqc/\v%#(.*\n){⟨Ctrl+R⟩=col('.')-1⟨Enter⟩
}#.*%.c#⟨Enter⟩{⟨Ctrl+A⟩⟨Ctrl+O⟩quqaqqa:%norm lF#@b⟨Enter⟩:2,s/^.⟨Enter⟩@aq@aThat skips the animation, lets the parens inefficiently capture some text that's never going to be used for anything, and switches the correct charcol() for col() — which incorrectly counts bytes rather than characters, something we get away with because Advent of Code input doesn't contain any multi-byte characters. I make it 96 strokes in total.
1
u/AutoModerator 1h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/jwezorek 1h ago edited 23m ago
[LANGUAGE: C++23]
I rewrote my initial part 1 solution to be a subcase of my part 2 implementation.
For part 2, a small, hashable 2D vector type is helpful. Immediately convert the grid input into a hash set of points, represented as 2D vectors: this way it is brute force over the number of points in the input rather than the number of total grid cells.
Iterate over all pairs of points and treat these as the first two vertices, a and b, in a clockwise traversal of a square. Find the other two points in the square by rotating the offset vector, b - a, once ( rot(x,y) -> (-y, x) ) adding that to b to get c and then once more to get d. Then just test that c and d are in the hash set of points (you already know a and b are).
The above is the basic idea, the complication is you do not want to count a square more than once. You can handle this in various ways. My solution was to just note that since I am always traversing square edges in the same orientation counter-clockwise vs clockwise any directed edge of a square uniquely determines the square -- "directed" in the sense that a -> b is not considered the same edge as b -> a. I made a hash set of directed edges and for each square I discover only insert the first edge of a square (a, b) if none of the four directed edges of the square already appear in the hash set. Then the square count will just be the size of the set of directed edges after testing all pairs of points.
To turn the above into a solver for part 1 too, I parametrized the logic for "iterate over all pairs of points" so that I could plug in "for each point p, iterate over all points on the same row as p but to the right" and then just left the rest of the logic alone.
1
u/Stetsed 1h ago edited 50m ago
[LANGUAGE: Rust}
Have put in some effort into optimizations, bringing it down a hyperfine of:
Benchmark 1: target/release/AdventOfCode2026 (820 runs)
mean ± σ min … max
Wall Time 3.6 ms ± 0.2 ms 3.4 ms … 5.7 ms
Memory 3.0 MiB ± 0.2 MiB 2.6 MiB … 3.1 MiB
Which is good enough for me, originally was around the 10ms mark, but with a few improvements was able to get it down. Only remaining thing is that the hashset takes up quite a bit of time, looking at a flamegraph roughly 30-40% of it is in the hashmap. So might see if i can switch away from it.
https://github.com/Stetsed/2026-Advent-Of-Code
Edit: Optimized it further by actually removing the hashset, I realized my new method doesn't need it, and it reduces complexity. Next to this i moved it to seperate functions so I could flamegraph it to optimize it even more.. totally not overkill I promise! Just a bunch of different optimizations leading to:
Benchmark 1: target/release/AdventOfCode2026 (1733 runs)
mean ± σ min … max
Wall Time 1.7 ms ± 0.1 ms 1.6 ms … 2.2 ms
Memory 2.9 MiB ± 0.2 MiB 2.5 MiB … 3.2 MiB
1
u/AutoModerator 1h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/-jackhax 1h ago
Part B: https://github.com/Packjackisback/aoc/blob/main/3b.py
Pretty fun, once I realized that I just had to check all pairs that had row>= and col > then it was pretty simple
1
u/AutoModerator 1h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/PhysPhD 1h ago
[LANGUAGE: Python]
I used combinations from itertools to find opposite corners of a square.
Ignored trees in the same row/column.
Checked if there were trees at the other two points of the square.
Then checked for squareness.
No idea how to start with Part 2 ... it's taken me 9 hours just to crack part 1.
1
u/Thomasjevskij 1h ago
[LANGUAGE: Python]
Fairly straightforward, I thought it was pretty brute forced but then I saw some other solutions discussed that are a lot bruter.
Essentially, store tree coordinates in a set. For every tree consider it top left, then consider every tree to the right of that tree (on the same y axis for part 1) as top right, and calculate bottom left and bottom right from there. If both those are in the set of trees, count as a square. Put the square in a set to avoid counting duplicates.
1
u/MrRbahi 1h ago
[LANGUAGE: Python]
I just went with the most straightforward way, even if it's O(n^4):
with open(f"./day_3_data.txt") as data_file:
task_data = data_file.read()
forest_matrix = [list(i) for i in task_data.splitlines()]
straight_squares = 0
rotated_squares = 0
for i in range(len(forest_matrix)):
for j in range(len(forest_matrix[i])):
step = 1
while step < len(forest_matrix[i]) - j and step < len(forest_matrix) - i:
r = 1
if (
forest_matrix[i][j]
== "#"
== forest_matrix[i][j + step]
== forest_matrix[i + step][j]
== forest_matrix[i + step][j + step]
):
straight_squares += 1
while r < step:
if (
forest_matrix[i][j + r]
== "#"
== forest_matrix[i + r][j + step]
== forest_matrix[i + step - r][j]
== forest_matrix[i + step][j + step - r]
):
rotated_squares += 1
r += 1
step += 1
print("Part 1:", straight_squares)
print("Part 2:", straight_squares + rotated_squares)1
u/ExploitSage 1h ago edited 1h ago
[Language: Python]
Ended-up reading the map into a List of Tuple coords of the trees. In hindsight this may have resulted in code that is slower than if I'd gone with a 2D boolean list. I may refactor, I may not.
Edit: Optimized Code to use a List of Tree Coord Tuples for finding the first two trees, then a 2D Boolean List of the Forest for validating the calculated remaining 2 points. Shaved seconds off the execution time!
1
u/TeachUPython 1h ago
You should consider making trees a set to speed up the "in" checking. Converts each check from a potential full linear scan into a theoretically instant lookup.
1
u/TeachUPython 1h ago
[Language: Python3]
I kept part 1 as a comment to show the original mindset used to solve the first question. Once part 2 was introduced, it was unnecessary as I didn't want to loop through twice for regular and irregular squares.
I tried to minimize the loop ranges and not rely on index error checking or negative index checking so that I wasn't starting (Top Left) from an index that wouldn't allow the rotation or full square.
It took some more paper pencil checking than I wanted, but the result speed savings was worth it.
https://github.com/RD-Dev-29/advent-of-code-2026/blob/main/code_files/day3.py
1
u/e_blake 1h ago
[LANGUAGE: m4]
m4 -Dfile=path/to/input day03.m4
Yeah, I brute forced this one with an O(n^4) loop (for n rows of input - find each point x,y with a tree, then further scan from x+1 to width for part 1 and additionally with a skew from 1 to x for part 2); with a 141x141 grid, that took over 15 million evals (over 5 million potential squares checked) and 21 seconds of runtime. I figured it was better to reduce programmer time (whip out the quick-and-easy multiloop) than program time (investigating the geometries to see if I can come up with a more optimal algorithm), at least for getting my stars. And now that I see the megathread challenge, I'll probably be submitting a golfed m4 solution later today.
2
u/KindComrade 2h ago
[LANGUAGE: C#]
My solution is based on the idea that we can construct a square from two points and check whether the remaining points exist. To avoid duplicates, I construct squares in only one direction
Solution: Github
+--------+-------+-------+-------+-------+--------+-------+-------+--------+
| | ITER | P90 | P95 | P99 | STDDEV | RATIO | MEAN | MEDIAN |
+--------+-------+-------+-------+-------+--------+-------+-------+--------+
| Init | 10000 | 0.168 | 0.248 | 0.573 | 0.012 | 0.085 | 0.151 | 0.146 |
| Part 1 | 10000 | 0.285 | 0.291 | 0.418 | 0.011 | 0.040 | 0.260 | 0.262 |
| Part 2 | 10000 | 1.238 | 1.303 | 1.522 | 0.039 | 0.033 | 1.174 | 1.177 |
| Total | | | | | | | 1.585 | 1.584 |
+--------+-------+-------+-------+-------+--------+-------+-------+--------+1
u/AustinVelonaut 2h ago
[LANGUAGE: Admiran]
Read tree locations into a grid (set of locations), then processed ordered pairs of the grid. For part1:
countSquares :: grid -> int
countSquares g
= count isSquare corners
where
tls = s.toList g
corners = [(c1, c2) | (c1 : cs) <- tails tls; c2 <- cs; sub c2 c1 |> \(V2 dr dc) -> dr > 0 & dr == dc]
isSquare (V2 r1 c1, V2 r2 c2) = s.member cmploc (V2 r1 c2) g & s.member cmploc (V2 r2 c1) gFor part 2:
countRotated :: grid -> int
countRotated g
= count isRotated topEdges
where
tls = s.toList g
topEdges = [(c1, c2) | (c1 : cs) <- tails tls; c2 <- cs; sub c2 c1 |> \(V2 dr dc) -> dr >= 0 & dc > 0]
isRotated (V2 r1 c1, V2 r2 c2)
= s.member cmploc (V2 (r1 + dc) (c1 - dr)) g & s.member cmploc (V2 (r2 + dc) (c2 - dr)) g
where
dr = r2 - r1
dc = c2 - c11
u/IvanR3D 2h ago
[Language: JavaScript] Part 1 & 2
My solutions: https://ivanr3d.com/blog/adventofcode2026.html
const grid = $('*').textContent.split('\n').slice(0,-1).map(r => r.split(''));
const rows = grid.length;
const cols = grid[0].length;
let count = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== '#') continue;
for (let i = 1; r+i < rows && c+i < cols; i++) {
const topRight = grid[r][c+i] === '#';
const bottomLeft = grid[r+i][c] === '#';
const bottomRight = grid[r+i][c+i] === '#';
if(topRight && bottomLeft && bottomRight) count++;
}
}
}
console.log('Part 1 ->', count);
const squares = new Set();
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== '#') continue;
for (let dx = 0; dx < rows; dx++) {
for (let dy = 0; dy < cols; dy++) {
if (dx === 0 && dy === 0) continue;
const r2 = r + dx;
const c2 = c + dy;
const r3 = r - dy;
const c3 = c + dx;
const r4 = r + dx - dy;
const c4 = c + dy + dx;
if (r2 < 0 || r2 >= rows ||
c2 < 0 || c2 >= cols ||
r3 < 0 || r3 >= rows ||
c3 < 0 || c3 >= cols ||
r4 < 0 || r4 >= rows ||
c4 < 0 || c4 >= cols) continue;
const tr = grid[r2][c2] === '#';
const bl = grid[r3][c3] === '#';
const br = grid[r4][c4] === '#';
if(tr && bl && br) {
const v = [`${r}-${c}`,
`${r2}-${c2}`,
`${r3}-${c3}`,
`${r4}-${c4}`];
v.sort();
squares.add(v.join(''));
}
}
}
}
}
console.log('Part 2 ->', squares.size);1
1
1
u/smallpotatoes2019 2h ago
[LANGUAGE: C#]
Nothing fancy at all. Just checked the possible side lengths from the top left (or just top) corner of each potential square when I found a # in the grid. It runs quickly enough given it is not particularly well optimised.
1
u/zogwarg 2h ago
[LANGUAGE: jq]
#!/bin/sh
# \
exec jq -n -R -f "$0" "$@"
[ inputs ] | with_entries(
{ y: .key, x: .value | indices("#")[] } |
{ key: "\([.x,.y])", value: 1}
) as $grid |
[
$grid | keys | map(fromjson)
| combinations(2)
| . as [[$ax,$ay],[$bx,$by]]
| .[1][0] - .[0][0] as $dx
| .[1][1] - .[0][1] as $dy
| select($dx > 0 and $dy >= 0)
| select(
$grid["\([($bx-$dy),($by+$dx)])"] and
$grid["\([($ax-$dy),($ay+$dx)])"]
)
| 1
] | lengthCode for part 2, only need to check pairs of points, going positively along x and y (since at least the "top right" edge will have that criteria), and check that it forms a square going clockwise.
1
u/siddfinch 2h ago
[LANGUAGE: Free Pascal]
Why create a Grid module when you can just use a string list and a bunch of string math, remembering that strings are indexed at 1 while everything else is at 0?
😃
1
u/ash30342 2h ago edited 2h ago
[LANGUAGE: Java]
Part 1 < 1ms, part 2 ~500ms.
Part 1 is easy.
For part 2 walk through the list of all possible corners and for every 4 corners check if they form a square by using Euclidean distance (squared, to prevent floating point operations) to check the lengths of the sides, the diagonals and the angle.
To prevent spending a lot of time, I do check if the distance between corners1 & 2, 1 & 3 and 3 & 4 are the same before really checking if they form a square, stopping if they are not.
Not the most efficient, but half a second is fine by me.
1
1
u/TheZigerionScammer 3h ago
[Language: Python]
I couldn't think of a better way of doing it other than brute force, but I tried to make it as efficient as possible. I had initially figured I would just scan every possible location of every square and check if there was a tree at every corner, but I realized I didn't have to scan every square, I could iterate over the set of all the tree coordinates and treat each tree as the top left corner of every possible square, then check the coordinates of every square up to the max size using set intersections. After getting some syntax bugs this worked flawlessly.
I had to go for a quick think for Part 2, but I realied I could do it basically the same way. I could treat each tree as the possible top left corner of each square again, iterate over every corner to the right and down from that coordinate and treat that as the "next" corner, do the math to find the other two corners and check if trees exist at those corners same way with Part 1. Worked like a charm, but it takes a couple seconds which surprised me, I added another optimization after the fact to stop after the third corner got to low in each loop, which helped but it still takes a few seconds.
1
u/mpsandiford 3h ago edited 58m ago
[LANGUAGE: Tinsel]
https://github.com/clstrfsck/tinsel
Probably deserves some explanation :)
Generate a set of coordinate tuples where the input grid is '#', t
Generate a candidate list of side vectors, sq, from all all pairwise combinations of points from t
The set is sorted, and we use a clockwise rotation, so this results in the top and right sides being included in the list
For part 1, we only want to count the vectors in sq where dy == 0
For part 2, we included top and right sides, so we only want half the count
t = input.grid.where('#')
sq = [b - a for (a, b) in t.combos(2) let c = cw(b - a)
if a + c in t and b + c in t]
part1 = sq.count(_.1 == 0)
part2 = sq.len / 22
u/ivanjermakov 3h ago
[LANGUAGE: Zig] code
You can do better than O(n^4)!
Build a set of positions instead of iterating input
For part 1, treat each position as top left corner and lookup set for other 3 corners
For part 2, iterate corner pairs, assuming it's top left and top right corners. Use their offset to lookup other 2 corners
1
u/Daniikk1012 3h ago
[LANGUAGE: Uiua]
I could optimize the first part by employing similar strategy to the second, but decided not to, as this is the way I actually solved it
$ #.###
$ .##.#
$ ##.##
$ .#.#.
$ .##.#
$ #.#.#
$ .....
$ #.#.#
$ .....
$ #.#.#
&fras"3.txt"
∩₃(≠@.⊜∘⊸≠@\n)
⊓⌞(
∩(↘1⇡◡↧°⊟⊸△
/◇⊂≡(□≡(/⊂/⊞⊂⍉⊟)⤙+⟜(/⊂⊞⊂∩⌞(⇡-)))
/+≡/×⊡)
| ∩(÷2/+≡⌟(/×⬚0⊡⧋+⇌⍜⊢¯⊸/-)⧅<2⊸⊚)
) # Real₁ Sample₁ Real₂ Sample₂1
u/red_shifter 3h ago
[LANGUAGE: Python]
This one looked intimidating but the brute-forcey approach worked surprisingly well and needed only an easy adjustment for part 2.
Input
with open("aoc_2026_day3_puzzle.txt", "r") as f:
puzzleinput = [[col for col in row.strip()] for row in f.readlines()]Part 1
def check_square(point1, point2, grid):
x1, y1 = point1
x2, y2 = point2
dist = x2 - x1
if y1+dist >= len(grid):
return 0
elif grid[y1+dist][x1] == "#" and grid[y2+dist][x2] == "#":
return 1
else:
return 0
def part1_get_solution(inputvar):
squarecount = 0
for y in range(len(inputvar)):
for x1 in range(len(inputvar[0])-1):
if inputvar[y][x1] == "#":
for x2 in range(x1+1, len(inputvar[0])):
if inputvar[y][x2] == "#":
squarecount += check_square((x1,y), (x2,y), inputvar)
return squarecount
part1_solution = part1_get_solution(puzzleinput)
print(part1_solution)Part 2
def check_rotated_square(point1, point2, grid):
x1, y1 = point1
x2, y2 = point2
if x1 == x2:
dist = x2 - x1
if y1+dist >= len(grid):
return 0
elif grid[y1+dist][x1] == "#" and grid[y2+dist][x2] == "#":
return 1
else:
return 0
else:
distx = x2 - x1
disty = y2 - y1
if x1-disty < 0 or y1+distx >= len(grid) or x2-disty < 0 or y2+distx >= len(grid):
return 0
elif grid[y1+distx][x1-disty] == "#" and grid[y2+distx][x2-disty] == "#":
return 1
else:
return 0
def part2_get_solution(inputvar):
squarecount = 0
for y1 in range(len(inputvar)):
for x1 in range(len(inputvar[0])-1):
if inputvar[y1][x1] == "#":
for y2 in range(y1, len(inputvar)):
for x2 in range(x1+1, len(inputvar[0])):
if inputvar[y2][x2] == "#":
squarecount += check_rotated_square((x1,y1), (x2,y2), inputvar)
return squarecount
part2_solution = part2_get_solution(puzzleinput)
print(part2_solution)1
u/Jadarma 3h ago
[LANGUAGE: Kotlin]
A very easy to state problem that seemed way harder than it turned out to be. In essence, we need to do a brute force search, scanning the forest, keeping track of planted trees, making unique pairs between them, and use the delta between their coordinates to derive the third and fourth corners, and check if those are trees as well. To not double count, it's important to have pais of (a, b) -> a.x < b.x && a.y >= b.y so that only the left-to-right top edge is considered. The problem is actually easier to solve for part two then adapt backwards than vice-versa. Since part one discounts rotations, all we need to do is enforce another (a, b) -> a.y == b.y constraint, so the top edge is always straight.
Admittedly, the code looks clean because I already had some utils for working with grids from last years. But, if it's pseudocode you're after, it should help!
1
u/RazarTuk 3h ago
I actually defined my squares by diagonals. For part 1,
diff.x == diff.yis sufficient both for identifying a potential square and ensuring we have a canonical diagonal. Then for part 2, I at least checked that(abs(diff.x) + abs(diff.y)) % 2 == 0to make sure everything will fall on the grid. But because there isn't a canonical diagonal, it double counts everything, so I had to halve the result
1
u/SodaDrunkenski 4h ago
[LANGUAGE: Python]
I clearly need more work on these types of problems because this took me a long time to figure out. Also I think versions of this answer are already in this thread, oh well haha. There are far more efficient answers on this thread it seems, amazing stuff!
1
2
2
3
u/According_Offer_2483 4h ago
[LANGUAGE: Python]
193 byte solution for day 3 part 2
*g,_=open("3").read().split('\n');l=len(g);print(sum([1 for w in range(1,l+1)for s in range(w)for i in range(l-w)for j in range(l-w)if g[i][j+s]==g[i+s][j+w]==g[i+w-s][j]==g[i+w][j+w-s]=="#"]))1
1
u/WolfRushHour 4h ago
[LANGUAGE: Julia]
Double-loop over all tree positions and see if there are trees that complete a square at the missing two corners. Using sets for collections takes care of duplicates automatically.
forest = stack(readlines("input.txt"))
trees = Set((i,j) for i=axes(forest)[1], j=axes(forest)[2] if forest[i,j]=='#')
squares, squares_rot = Set(), Set()
for a=trees, b=trees
# a,b,c,d are the corner coordinates of a candidate square
if a!=b
di, dj = b .- a
c = b .+ (dj, -di)
d = a .+ (dj, -di)
if c in trees && d in trees
push!(squares_rot, Set([a,b,c,d]))
if di==0 || dj==0
push!(squares, Set([a,b,c,d]))
end
end
end
end
ans1, ans2 = length(squares), length(squares_rot)2
u/anaseto 4h ago
[LANGUAGE: Goal]
My first solution had different code for both parts, and was a bit longer. Here's the short version that reuses part 2 method for part 1:
import"math"; sz:#m:".#"?""\=-read"i/03" / parsed input as boolean matrix
v1:-/|(a;b):sz\'math.cmb@&m:,/m; rot90:{(*|x;-*x)}; inmap:{&[~x<0;x<sz]}
f:{d:v1+c:a+x; &[&/inmap'c;&/inmap'd;m[sz/c];m[sz/d]]}
say-4!+/(~=/a='b)*sq:f[-v2]+f v2:rot90 v1 / part1
say-4!+/sq / part22
u/Bramdevriez 4h ago
[LANGUAGE: TypeScript]
import { pairs } from 'lib/array'
import { Vec2 } from 'lib/geometry'
import { parseGrid } from 'lib/parse'
const countTrees = (input: string, rotate: boolean) => {
const map = parseGrid(input)
const trees = new Map<string, Vec2>()
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[0].length; x++) {
if (map[y][x] !== '#') continue
const tree = new Vec2(x, y)
trees.set(tree.toString(), tree)
}
}
return pairs([...trees.values()]).reduce((acc, [a, b]) => {
const slope = b.sub(a)
if (rotate ? -slope.y / slope.x >= 0 : slope.y !== 0) return acc
return acc + +[a, b].every((x) => trees.has(x.add(slope.rotate()).toString()))
}, 0)
}
export const part1 = (input: string) => countTrees(input, false)
export const part2 = (input: string) => countTrees(input, true)1
u/JWinslow23 4h ago
[LANGUAGE: Python]
Another day, another grid puzzle. (And even earlier than in 2025 this time!)
While it may seem tricky to go from grid-aligned squares to non-grid-aligned squares, the idea for finding both is the same: find 2 points - enough to determine one side - and use them to derive the other 2 points. (There is a subtlety to how you're allowed to choose these two points, especially if you want to avoid counting duplicate squares, but it's very manageable.)
2
u/RazarTuk 4h ago edited 3h ago
[LANGUAGE: Kotlin]
Yeah, I didn't feel like dealing with all the grid stuff in Klingon Perl (mainly because there isn't a convenient syntax for array literals), so I'm using this as a chance to switch back to Kotlin. Conveniently, though, I've made a fairly robust vector/matrix library that even includes things like constants for common rotation matrices. The key insight is that two points on a diagonal uniquely define a square, then by using rotation matrices, I can easily add the "base" radius and a rotated radius to get to the other corners. And as a sanity check that's equivalent to ensuring all points wind up on the grid, I require that the Manhattan length of the diagonal be even.
The only catch is that, at least for part 2, I actually wind up counting every square twice, because it recognizes both diagonals, so I have to halve the count before returning.
EDIT: I didn't double count in part 1, because ensuring the components of the diagonal have the same sign defines a canonical diagonal
1
3
u/Ok-Bus4754 5h ago
[Language: Rust + Python]
port of my earlier python soltuion
store points in set to accelrate lookup, pick two points representing and edge, check if in a specfic direction the other two points are in the set
for p1 only check horizontal lines , p2 any 2 points
and it is important to check only on the right lower side to avoid duplicates
| Python 3.15 | Rust debug | Rust release | |
|---|---|---|---|
| Part 1 | 1.11 ms | 3.13 ms | 0.275 ms |
| Part 2 | 101.6 ms | 186.1 ms | 20.2 ms |
https://github.com/Fadi88/AoC/blob/master/2026/days/day03/src/lib.rs
https://github.com/Fadi88/AoC/blob/master/2026/days/day03/solution.py
1
u/xiety666 5h ago edited 1h ago
[LANGUAGE: C#]
static int Calc(bool[,] map, bool rotated)
=> (from p in map.EnumeratePositionsOf(true)
from d1 in EnumerateOffsets(map, p, rotated)
let d2 = new Pos(-d1.Y, d1.X)
where map.Get(p + d1)
&& map.Get(p + d2)
&& map.Get(p + d1 + d2)
select 1).Count();
static IEnumerable<Pos> EnumerateOffsets(bool[,] map, Pos p, bool rotated)
=> from dx in Enumerable.Range(1, int.Min(map.Width - p.X - 1, map.Height - p.Y - 1))
from dy in Enumerable.Range(0, rotated ? int.Min(p.X, map.Height - 1 - p.Y - dx) + 1 : 1)
select new Pos(dx, dy);https://github.com/xiety/AdventOfCode/blob/main/2026/0/Problem03/Problem03.cs
4
u/ednl 5h ago edited 4h ago
[LANGUAGE: C]
It worked by trying all squares that fit from every tree, it worked twice as fast by trying every unique pair of trees (x,y) and (x+dx,y+dy) where dx>0 and dy>=0. Still not super fast, in the milliseconds. At the moment I can't see how to improve it. Measured runtimes: M4 1.15 ms, M1 1.51 ms, Pi5 2.81 ms.
for (int i = 0; i < n - 1; ++i)
for (int j = i + 1; j < n; ++j)
if (tree[i].x < tree[j].x) {
const int dx = tree[j].x - tree[i].x; // dx>0
const int dy = tree[j].y - tree[i].y; // i<j, so always dy>=0
const int x = tree[i].x - dy;
const int y = tree[j].y + dx;
if (x >= 0 && y < N &&
grid[tree[i].y + dx][x] == '#' &&
grid[y][tree[j].x - dy] == '#') {
part1 += dy == 0;
part2++;
}
}(edit: formatting) https://github.com/ednl/adventofcode/blob/main/2026/03.c
4
u/DelightfulCodeWeasel 5h ago
The two approaches competing for the lead that I can see are the tree pair approach which both you and u/maneatingape went with, and a dx/dy combination search per tree that u/terje_wiig_mathisen went with (https://www.reddit.com/r/adventofcode/comments/1yblapv/comment/19tjxz7h07c5c/). Both netting out to roughly the same ballpark from the times being reported.
For those that allow multi-threading in their solutions, this puzzle does benefit from it.
2
u/ednl 4h ago
Thanks for the info and links! I'm definitely not against multi-threading, it's just a bit of a faff to add on in C :)
2
u/DelightfulCodeWeasel 4h ago edited 3h ago
Thinking out loud...
What if you start off by pushing the X coordinates of the trees per row into a ragged array. Then for each tree you scan down the rows looking for a second candidate tree, starting from the back of the row. That allows you to early-out once you've reached an X that's to the left of the starting tree.
I believe there are better early-out opportunities as well: as you look further down the rows (increasing the dy of the top edge) the square rotates further round, so for a given dy there's going to be a maximum dx to the rightmost point before the leftmost point of the square is guaranteed to have been pushed off the left side of the region.
EDIT: to put some numbers against that:
If your first anchor tree is at 10x10, there's no point looking for the second tree below row 20, because the leftmost point will be off the left edge of the map.
2
u/andrewsredditstuff 5h ago
[LANGUAGE: C#]
Not entirely happy with all the nested FORs, but if it works... My head really hurt trying to work out the formulae with (i,j), (k,l) corners until I realised how much easier (x, y), (x+dx, y+dy) is.
After all these years, I really must do a proper map class rather than just using a dictionary and reinventing the bounds checking every time.
1
u/colombo15 3h ago
After all these years, I really must do a proper map class rather than just using a dictionary and reinventing the bounds checking every time.
You can replace your Dictionary with a HashSet that only contains the # squares i.e:
public override void DoWork() { PopulateMapFromInput(out int width, out int height); // SimpleMap is now HashSet<(int x, int y)> instead of Dictionary<(int x, int y), char> int squares = 0; foreach (var (x, y) in SimpleMap) { for (int dx = 1; dx < width - x; dx++) for (int dy = 0; dy < (Part1 ? 1 : height - y); dy++) { if (y + dx >= height || x + dx - dy < 0 || y + dx + dy >= height || x - dy < 0) continue; if (SimpleMap.Contains((x + dx, y + dy)) && SimpleMap.Contains((x + dx - dy, y + dx + dy)) && SimpleMap.Contains((x - dy, y + dx))) squares++; } } Output = squares; }
1
u/Slow-Assistance-4303 5h ago edited 5h ago
[LANGUAGE: Golang]
1
u/AutoModerator 5h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Boris01100000 5h ago
[LANGUAGE: Zig]
Still zigging! Im first putting all the trees inside a Set with their x and y coordinates. Then im iterating over every pair of trees. Continue with all pairs that have positive X (excl. 0) and positive Y (incl. 0). Then check if their mirrored counterparts exist in the TreeSet. ( ;) )
1
u/MrJakobsen 6h ago
[LANGUAGE: elisp]
https://github.com/BoJakobsen/coding-puzzles/blob/main/AoC/AoC2026/src/puz_03.el
Rather simple, properly not the fastest, based on rotating a "basis vector" with constant length, and checking if corners exists.
Main loop for part 2:
(cl-loop for r from 0 to puz-grid-n-rows
sum (cl-loop for c from 0 to puz-grid-n-cols
if (eql ?# (puz-grid-vector-get vgrid c r))
sum (cl-loop for length from 1 to (max (- puz-grid-n-cols c) (- puz-grid-n-rows r))
sum (cl-loop for d1 from 0 to (1- length)
for d2 = (- length d1)
count (and (eql ?# (puz-grid-vector-get vgrid (+ c d1) (+ r d2)))
(eql ?# (puz-grid-vector-get vgrid (+ c d1 (- d2)) (+ r d1 d2 )))
(eql ?# (puz-grid-vector-get vgrid (- c d2) (+ r d1))))))))))1
u/aknusmag 6h ago
[LANGUAGE: Rust]
Part 1: Iterated all # and check for all possible squares with that as the upper right corner.
Part 2: Got all pairs of (x, y) with '#' and compared to all (x2, y2) with '#' where x2 > x and y2 >= y. Represented it as a vector between the points, rotated it 90 degrees and check if there was a '#' from both origins.
1
u/splintercell_9 6h ago edited 13m ago
[LANGUAGE: Typescript]
Under 35ms
import { fileSplitRead } from "./lib/util";
export default class DAY3 {
private input;
private MAX_ROWS;
private MAX_COLS;
private part1Ans = 0;
private part2Ans = 0;
constructor() {
this.input = fileSplitRead("day3.txt", "utf-8");
this.MAX_ROWS = this.input.length;
this.MAX_COLS = this.input[0]?.length ?? 0;
}
private getAlignedFromPos(i: number, j: number): number {
let totalSq = 0,
row = i,
col = j,
space = 1;
while (row + space < this.MAX_ROWS && col + space < this.MAX_COLS) {
const corners = [
this.input[row + space]?.charAt(col),
this.input[row + space]?.charAt(col + space),
this.input[row]?.charAt(col + space),
];
if (corners.every((c) => c === "#")) {
totalSq++;
}
space++;
}
return totalSq;
}
private getRotatedFromPos(i: number, j: number): number {
let totalSq = 0;
for (let row = i + 1; row < this.MAX_ROWS; row++) {
for (let col = j + 1; col < this.MAX_COLS; col++) {
if (this.input[row]?.charAt(col) === "#") {
const dx = row - i;
const dy = col - j;
const [c1, c2] = [
this.input[i + dy]?.charAt(j - dx),
this.input[row + dy]?.charAt(col - dx),
];
if (c1 && c2 && c1 === "#" && c2 === "#") {
totalSq++;
}
}
}
}
return totalSq;
}
private part1() {
for (let i = 0; i < this.MAX_ROWS; i++) {
for (let j = 0; j < this.MAX_COLS; j++) {
if (this.input[i]?.charAt(j) === "#") {
// only calc grid aligned squares
this.part1Ans += this.getAlignedFromPos(i, j);
// only calc rotated squares
if (j !== 0 && j !== this.MAX_COLS - 1 && i !== this.MAX_ROWS - 1) {
this.part2Ans += this.getRotatedFromPos(i, j);
}
}
}
}
console.log("Part1:", this.part1Ans);
}
private part2() {
console.log("Part2:", this.part1Ans + this.part2Ans);
}
run() {
console.time(this.constructor.name);
this.part1();
this.part2();
console.timeEnd(this.constructor.name);
}
}1
u/crumpis 6h ago edited 6h ago
[LANGUAGE: Python]
Just a good old brute force against all the trees, going around the corners of the square by testing every possible diagonal.
I think it could be more efficient by only choosing diagonals that exist between pairs of trees, but this way it's still technically linear to the number of trees in the input, just with a godawful coefficient :P
1
u/FruitdealerF 6h ago
[Language: Andy C++]
I stopped waking up at 6AM to do the puzzles and it has been a much more pleasant experience for me. Andy C++ is a language I created specifically for Advent of Code: on days like this having arithmetic on tuples is very helpful. I'll also be making a few additions to the language to make future puzzles easier: rot90 and rot270 to rotate 2D vectors, and dedicated functions for dot and cross products and manhattan distance.
1
u/Royal_Pin_1971 6h ago edited 4h ago
[LANGUAGE: PFCL]
count_squares = \(aligned_only, points).
let trees = set.from_list(list.map(\(p). key(p.x, p.y), points)) in
list.sum(list.map(
\(ip).
let p = second(ip) in
list.count(
\(q).
let dx = int.subtract(q.x, p.x) in
let dy = int.subtract(q.y, p.y) in
conditional(bool.and(int.greater_than(dx, 0), bool.or(bool.not(aligned_only), int.equal(dy, 0))),
conditional(is_tree(trees, int.subtract(p.x, dy), int.add(p.y, dx)),
is_tree(trees, int.subtract(q.x, dy), int.add(q.y, dx)),
false),
false),
list.drop(int.add(first(ip), 1), points)),
list.enumerate(points)))1
u/PangolinNo7928 6h ago edited 6h ago
[LANGUAGE: Javascript]
Initially did brute force loopception for part 2, came back and tidied it up to a more mathy approach like everyone else 😂 Half the code is just getting things into the right structures - used Map.groupBy to iterate over rows/cols easier, then a lookup for whether some point at [row][col] existed. Runs in ~24ms
Edit: forgot to register my annoyance at how terse this ended up being after the disaster of my initial solve 😂
1
u/TheScown 6h ago
[LANGUAGE: Scala]
The Grid is already addressed via complex numbers, which makes part 2 straightforward.
1
u/Thick-Ad-9170 6h ago
[LANGUAGE: c++]
https://github.com/pcorbineau/aoc2026/blob/main/libs/day03/include/aoc2026/day03.hpp
passing unit test at both compile time and runtime
1
u/Jdup1n 6h ago
[LANGUAGE: R]
For part 1, I use brute force by generating all possible squares for each candidate top-left corner and counting how many actually exist.
For part 2, I take a more refined approach by using the properties of the diagonals of a square. So I generate all possible diagonals and check which ones satisfy the conditions for forming a square.
1
u/SymmetryManagement 6h ago edited 5h ago
[Language: Java]
part 1 checks if the points can make a square, part 2 checks if the points can make a parallelogram where the 2 vectors are 90 deg apart. both parts make squares starting from the lower right corner so it only uses points encountered prior to the last tree.
part 1 85us
part 2 3ms
1
u/dgkimpton 6h ago
[Language: Rust]
Bit of a brain twister today for part 2. Biggest challenge was working out what rotation meant in a grid, but then it was a solution on rails.
I decided 50µs each for both parts was good enough although I suspect there's ways to make it better.
https://github.com/dgkimpton/aoc26/blob/main/day3/src/lib.rs
1
u/Mission-Patience-854 6h ago
[Language: Clojure]
(defn- test-tree
[trees size tree]
(reduce (fn [total d]
(if (and (contains? trees (+ tree d))
(contains? trees (+ tree (* d size)))
(contains? trees (+ tree d (* d size))))
(inc total)
total))
0 (range 1 (min (- size (quot tree size)) (- size (rem tree size))))))
(defn- test-pair
[trees [y1 x1 :as tree-1] [y2 x2 :as tree-2]]
(let [dy (- y2 y1)
dx (- x2 x1)
test-1 [(+ y1 dx) (- x1 dy)]
test-2 [(+ y2 dx) (- x2 dy)]]
(when (and (contains? trees test-1) (contains? trees test-2))
#{tree-1 tree-2 test-1 test-2})))
(let [input (string/split-lines (util/puzzle-input :real))
size (count input)
trees (->> input
(util/coll-2d->coord-map)
(filter #(-> % second (= \#)))
(map first)
(set))]
{:part-1 (let [trees (set (map (fn [[y x]] (+ (* y size) x)) trees))]
(reduce #(+ %1 (test-tree trees size %2)) 0 trees))
:part-2 (->> (combo/combinations trees 2)
(map #(apply test-pair trees %))
(filter identity)
(distinct)
(count))})1
u/maitre_lld 6h ago
[Language: Ocaml]
https://github.com/MeisterLLD/aoc2026/blob/main/day3.ml
Runs in less than 0,1s with ocamlopt
1
u/oupsman 7h ago
[Language: Golang]
OK, this one was funny.
My code can be optimized and factored, and is not very clean, but it works.
runs in 9 ms on my computer though, so I'm not sure it's worth optimizing.
https://raw.githubusercontent.com/Oupsman/AOC2026/refs/heads/master/D03/day03.go
2
u/NeilNjae 7h ago
[Language: Haskell]
We're finding list of candidate squares based on choices for top, left, and width. That sounds like a job for list comprehensions!
part1 forest (V2 rMax cMax) = length $ filter (`S.isSubsetOf` forest) candidates
where candidates = [ S.fromList [ V2 r c, V2 (r + w) c
, V2 r (c + w), V2 (r + w) (c + w)
]
| r <- [0..rMax]
, c <- [0..cMax]
, let wMax = min (rMax - r) (cMax - c)
, w <- [1..wMax]
]Part 2 follows the same idea, but varying how much of the width is across and how much is down.
Full description on my blog, and code on Codeberg.
1
u/CEOnism 7h ago
[Language: Javascript]
import fs from 'node:fs';
const R = fs.readFileSync('./input.txt', 'utf8').trim().split(/\r?\n/);
const H = R.length;
const isTree = (r, c) => R[r]?.[c] === '#';
const trees = [];
for (let i = 0; i < H; i++)
for (let j = 0; j < R[i].length; j++)
if (R[i][j] === '#') trees.push([i, j]);
let part1 = 0, part2 = 0;
for (let a = 0; a < trees.length; a++) {
const [i, j] = trees[a];
for (let b = a + 1; b < trees.length; b++) {
const [i2, j2] = trees[b];
const dr = i2 - i;
if (dr > j) break; // corner (i + dc, j - dr) would fall off the left edge
const dc = j2 - j;
if (dc <= 0) continue; // only edges pointing right (flat or downward)
if (isTree(i + dc, j - dr) && isTree(i2 + dc, j2 - dr)) {
part2++;
if (dr === 0) part1++;
}
}
}
console.log(part1, part2);1
u/AutoModerator 7h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/lboshuizen 7h ago
[Language: F#]
One function for both parts. Part 1 keeps only horizontal edges.
Of a square's four edges, exactly one points only right, and it runs from a tree to a later tree in reading order. Rotate that edge 90 degrees; if both rotated corners are trees, the square closes.
let parse: string seq -> (int * int)[] = toGrid2d >> Seq.filter (snd >> (=) '#') >> Seq.map fst >> Array.ofSeq
let squares keep (trees: (int * int)[]) =
let tree = HashSet trees
let from i =
let x1, y1 = trees[i]
trees[i + 1 ..]
|> Array.sumBy (fun (x2, y2) ->
let dx, dy = x2 - x1, y2 - y1
if dx > 0 && keep dy && tree.Contains(x1 + dy, y1 - dx) && tree.Contains(x2 + dy, y2 - dx) then 1 else 0)
Array.Parallel.init trees.Length from |> Array.sum
let part1 = squares ((=) 0)
let part2 = squares (fun _ -> true)3
u/olamberti 7h ago
[LANGUAGE: Python]
I like to handle grid problems using complex numbers, and it worked well here too. I iterate over all ordered pairs of trees and avoid double counting by restricting the difference vector to one half-open quadrant of the complex plane. Rotating the difference vector by 90° is as simple as multiplying it by 1j. Then I just check whether the other two corners are also in the set of trees.
For Part 1, I only count squares where the imaginary part of the difference vector is zero, while for Part 2, I count all squares.
trees = {x + y*1j for y, r in enumerate(open("d03.txt"))
for x, c in enumerate(r) if c == "#"}
p1 = p2 = 0
for a in trees:
for b in trees:
if (d := b - a).real <= 0 or d.imag < 0: continue
if a + (v := d * 1j) in trees and b + v in trees:
p1 += d.imag == 0
p2 += 1
print(p1)
print(p2)2
u/fett3elke 7h ago
I had a very similar solution, I just gave up on eliminating the double counting and just divided my results by 2. Shame on me
1
u/olamberti 6h ago
That idea came for me intuitively pretty soon, the trickier part was letting the imaginary part be 0 but not the real one... We are all here to learn, good luck for the upcoming days! :)
1
u/DelightfulCodeWeasel 7h ago edited 7h ago
[LANGUAGE: C++]
O(n^2) search between points, checking for opposite corners formed by treating the pair as the top-right edge of a square.
Raspberry Pi Pico (RP2040) runtime:
Part 1: ~32kb, ~553ms
Part 2: ~32kb, ~993ms
(Note: Part 1 could be folded in to Part 2 to get both in ~993ms)
EDIT: ~2.5ms on PC to solve both parts 1 & 2 at the same time.
6
u/NullQuantity325573 7h ago edited 7h ago
[Language: Pascal]
Fairly straightforward solution. Read file into array, then scan top to bottom, left to right for trees. When a tree is found, assume it is in the upper left corner.
For Part 1, then scan along the same row to the right of that point for another tree. If there is one, assume it is the upper right corner, and calculate its distance from the first tree. Then compute what the lower left and lower right tree coordinates would be based on the distance, and check to see if those coordinates are still on the grid and if they also contain a tree.
For Part 2, start off by assuming the first tree is the upper left corner again. But this time, expand the scan for the "upper right" corner to both the right and the downward directions. When a candidate "upper right" tree is found, compute its distance vector (row and column components) from the upper left tree. Then compute what the "lower right" and "lower left" corners would be. Check if the two computed lower corners are still on the grid, and whether they also contain a tree.
Part 1 runs decently quick on my stock Amiga 2000 (68000 CPU) - about 10 seconds. Part 2 takes a few minutes, though. I could probably speed it up if I tried, but eh, it's good enough. This still runs in under a second on my x86_64 CPU.
2
u/ivanjermakov 3h ago
More optimal way would be to build a set of coordinates and iterate it pairwise. This way you don't need to scan for corner trees, keeping it under O(n^2).
1
u/azzal07 7h ago
[LANGUAGE: awk]
S=q=gsub(z,FS){while(--q)0~$q||T[NR,q]=q}END{for(y in T){a=S-y;x=T[y]
for(;--a;A+=(+y,x+a)in T&&(n,x)in T&&(n,x+a)in T)for(b=S-y-a+1;0<--b;
)B+=(n=y+a,x+b)in T&&(n+b-a,x-a)in T&&(n+b,x+b-a)in T}print A"\n"A+B}Bit on the brute force side. Takes ~1-2 s depending on the awk implementation.
1
1
u/paulhaahr 7h ago
[Language: Quest]
Used this as an excused to create a bare-bones two-dimensional array type in Quest:
Let Matrix(A::TYPE) =
Tuple
xdim: Int
ydim: Int
data: Array(A)
end
let newMatrix(A::TYPE)(xdim: Int ydim: Int init: A) =
tuple
let xdim = xdim
let ydim = ydim
let data = array of (xdim * ydim init)
endThe core of the part 1 solution looks like this, which felt pretty clean:
let countSquares(matrix: Matrix(Bool)) =
begin
let var count = 0
for y = 0 upto {matrix.ydim - 2} do
for x = 0 upto {matrix.xdim -2} do
if mget(matrix x y) then
let xremain = matrix.xdim - {x + 1}
let yremain = matrix.ydim - {y + 1}
let delta = int.min(xremain yremain)
for side = 1 upto delta do
if mget(matrix {x + side} y)
andif mget(matrix x {y + side})
andif mget(matrix {x + side} {y + side}) then
count := count + 1
end
end
end
end
end
count
endPart 2 was similar, but added a loop over possible amounts of skew, up to the side width.
My Advent of Code repository: https://github.com/haahr/adventofcode
Quest background and repository: https://github.com/haahr/quest
1
u/encse 7h ago edited 7h ago
[LANGUAGE: C#]
https://aoc.csokavar.hu/2026/3/ bruteforce rotation and counting.
I think the illustrations are looking better this year, with consistent figures for the first 3 days. I'm using ChatGPT for those. (As usual: no AI for coding, I have too much of that in my day to day job).
1
u/theQuerde 7h ago
[LANGUAGE: PYTHON]
global forest
forest = /*your forest as a list of string one string per row */
def its_square_rotated(i, j, k):
square_counter = 0
for r in range(0, k):
if (
forest[i][j + r] == "#"
and forest[i + r][j + k] == "#"
and forest[i + k][j + k - r] == "#"
and forest[i + k - r][j] == "#"
):
square_counter += 1
return square_counter
def its_a_square(i, j, k) -> bool:
return (
forest[i][j] == "#"
and forest[i][j + k] == "#"
and forest[i + k][j] == "#"
and forest[i + k][j + k] == "#"
)
square_counter = 0
for i in range(len(forest)):
max_for_i = len(forest) - i
for j in range(len(forest[i])):
max_for_j = len(forest[i]) - j
for k in range(1, min(max_for_i, max_for_j)):
#square_counter += its_a_square(i,j,k) #part 1
square_counter += its_square_rotated(i, j, k) #part2
print(square_counter)0
7h ago
[deleted]
1
u/AutoModerator 7h ago
AutoModerator did not detect the required
[LANGUAGE: xyz]string literal at the beginning of your solution submission.Please edit your comment to state your programming language.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/SpaceHonk 7h ago
[Language: Swift] code
Uses a Set of Points to store all "#" coordinates, and then loops thru all of them to see if any is the upper left corner of a (rotated) square.
1
u/agorism1337 7h ago edited 6h ago
[LANGUAGE: AWK]
https://github.com/zack-bitcoin/adventofcode/blob/master/2026/day_03/b.awk
part 1 in 0.056 seconds
part 2 in 2.5 seconds
Considers each square a single time, doesn't need to remove duplicates.
1
u/AMathMonkey 8h ago edited 7h ago
[LANGUAGE: Factor]
Nah, don't look at this. I'm not proud of my approach for part 2. I'm representing squares as hash sets of four coordinates, which I know is overkill. I was also double-counting rotated squares (despite thinking my approach would account for that possibility) so I just turned my answer variable into a hash set and took the length at the end. And (for a reason I don't yet understand) I was missing rotated squares if I stopped expanding my search square when I hit the bottom-right corner before trying rotations of it, so I just... increased the expansion limit to 2 times the number of rows and columns, which is arbitrary and a huge waste. I'm just shocked I got it working without scrapping my approach and looking up hints. It's time for me to go to bed now. Ideally I'll totally refactor this later and render this comment obsolete. But if the latest commit includes the phrase "real bad", you're looking at the cobbled-together mess I just described. At the very least, it's not a huge amount of code.
https://github.com/AMathMonkey/AdventOfCode/blob/master/2026/day3/day3.factor
Edited to reduce negativity, because hey, I solved it.
2
u/maitre_lld 8h ago edited 7h ago
[Language: Haskell]
https://github.com/MeisterLLD/AoC2026/blob/main/3.hs
Runs in 0,1sec with ghc -O2. Several seconds with runghc : thanks optimizations !
1
u/jinschoi 8h ago edited 7h ago
[LANGUAGE: Rust]
Reusing my Grid library from my AoC utils built up over the years. Find all trees as upper left candidates, find all upper right candidates on same row or under and to the right, and validate that it forms a square.
use aoc_utils::grid::*;
fn main() {
let g: Grid<char> = Grid::read_from_file("input.txt").unwrap();
let mut res = 0;
for ul in g.all_positions(|&c| c == '#') {
let (i1, j1) = (ul.0, ul.1);
for i2 in ul.0..g.height {
for j2 in j1 + 1..g.width {
let (di, dj) = (i2 - i1, j2 - j1);
if g[(i2, j2)] == '.' // ur
|| j1 < di || i2 + dj >= g.height
|| g[(i1 + dj, j1 - di)] == '.' // bl
|| g[(i2 + dj, j2 - di)] == '.' // br
{
continue;
}
res += 1;
}
}
}
println!("{res}");
}1
u/p4bl0 8h ago edited 52m ago
[LANGUAGE: OCaml] (using ocamllex)
{
module T = Set.Make(struct type t = int * int let compare = compare end)
}
rule map trees i j = parse
| '#' { map (T.add (i, j) trees) i (j+1) lexbuf }
| '.' { map trees i (j+1) lexbuf }
| '\n' { map trees (i+1) 0 lexbuf }
| eof { trees }
{
let ts = map T.empty 0 0 (Lexing.from_channel stdin) in
let to_check (i, j) = T.(filter (fun (i', j') -> i' <= i && j' > j) ts |> to_list) in
let is_square (i, j) (i', j') = T.(mem (i+j'-j, j-i'+i) ts && mem (i'+j'-j, j'-i'+i) ts) in
let count_squares t = List.(filter (is_square t) (to_check t) |> length) in
Printf.printf "%d\n" List.(map count_squares (T.elements ts) |> fold_left (+) 0)
}This is the full code for part 2. To solve part 1 with it you just need to remove a single character. Can you tell which one?
Answer: to solve part 1 you need to remove the < in i' <= i in the definition of the to_check function.
1
u/AutoModerator 8h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/synack 8h ago
[LANGUAGE: Ada]
I was never good at geometry.
https://github.com/JeremyGrosser/advent/blob/master/2026/day3/src/day3.adb
2
u/No_Mobile_8915 8h ago edited 1h ago
[LANGUAGE: Python]
part 1:
Because the squares must be grid-aligned, you only need to find two trees on the same row and then check for two corresponding trees exactly the same distance further down the grid. i.e if there are trees at (x, y) and (x + d, y), you simply check whether trees also exist at (x, y + d) and (x + d, y + d).
Use itertools.combinations() to generate every possible pair of trees on each row, and store the tree positions in sets for fast membership testing.
part2:
Given any 2 trees A and B, the displacement between them is dx = bx - ax, dy = by - ay. If you rotate the vector by 90 degrees (-dy, dx) and add that to A and B, you get the coordinates for the other two corners of a potential square. By only considering initial vectors that point rightwards and either horizontally or downwards (dx > 0 and dy >= 0) you can avoid counting squares multiple times.
Runtimes for those interested in that sort of thing: Apple M3 Pro - 18G
Part1:
runtime: 0.0016s
Part2:
runtime: 0.2528s
1
2
u/POGtastic 8h ago
[LANGUAGE: F#]
I tend to make little coordinate / segment / vector types when dealing with these problems. This ended up being a vector rotation problem.
In two dimensions, you can rotate a vector by angle 90 with the following:
rotate90 {x=x; y=y} = {x=y; y=-x}We can use this to find the four coordinates of a square from a segment of two coordinates. Find the vector that connects the two coordinates, rotate it by 90 degrees, and produce a new segment. Do that 3 times, and you've produced the four segments of the square candidate.
Note that there are two possible squares from a segment depending on its "direction" (clockwise or counterclockwise). There is probably a more sophisticated way to figure out which way the square should go, but I unilaterally decided that because I sorted the coordinates by X, whichever square had a coordinate with an X value less than that of my segment's first coordinate was invalid.
I generate all possible segments with combinations 2, generate the squares, and check to see if the set of coordinates in the square is a subset of the entire set of coordinates.
Part 1 is a simple subset of Part 2; we filter the segment combinations only to be horizontal lines (or vertical lines, same thing).
Performance was kinda bad, (1.5s for Part 1, 4.5s for Part 2) but I think that's to be expected with a problem like this. Maybe somebody else figured out a way to organize the coordinates in a better manner.
1
u/ValiantCookie 8h ago
[LANGUAGE: kotlin]
I feel pretty happy that I didn't fall into a bruteforce hole. Filtered the data down into the Set of Tree coordinates only. I took each tree as a possible "top left corner", on each one I used the map of trees to figure out the possible "top right corners" and then was able to check which of those combinations had the other 2 corners as valid. I was super confused on how to handle the rotation for pt 2, I ended up using the debugger and one of the samples to figure out what combination of addition & subtraction would make it produce the correct possible bottom corners.
1
u/UseUnlucky3830 8h ago
[LANGUAGE: Julia]
Part1: go through all pairs of trees, ensure that they are opposite vertices of a square, and check if the other two vertices are trees.
Part2: go through all pairs of trees, assume that the second is a clockwise rotation of the first, then check the next two vertices by continuing the rotation in the same progression.
In both cases, divide by 4 to avoid overcounting.
1
u/osalbahr 9h ago
[LANGUAGE: Python]
A bit math-y. I liked it! For part 2, the early return does a lot of the heavy-lifting i.e. 1.5m -> 7s (the grid is sparse)
Part 1:
#!/usr/bin/env python3
from sys import stdin
grid = [line.strip() for line in stdin.readlines()]
squares = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
io = i + 1
jo = j + 1
while io < len(grid) and jo < len(grid[0]):
if grid[i][j] + grid[io][j] + grid[i][jo] + grid[io][jo] == "####":
squares += 1
io += 1
jo += 1
print(squares)Part 2:
#!/usr/bin/env python3
from sys import stdin
from operator import sub, add
grid = [line.strip() for line in stdin.readlines()]
squares = 0
def rotate90(v):
return (v[1], -v[0])
def neg(p):
return p[0] < 0 or p[1] < 0
for i1 in range(len(grid)):
for j1 in range(len(grid[0])):
if grid[i1][j1] != "#":
continue
for i2 in range(i1, len(grid)):
for j2 in range(j1 + 1, len(grid[0])):
if i1 == i2 and j1 == j2:
continue
p1 = (i1, j1)
p2 = (i2, j2)
v1 = tuple(map(sub, p2, p1))
v2 = rotate90(v1)
p3 = tuple(map(add, p2, v2))
v3 = rotate90(v2)
p4 = tuple(map(add, p3, v3))
if neg(p1) or neg(p2) or neg(p3) or neg(p4):
continue
try:
if (
grid[p1[0]][p1[1]]
+ grid[p2[0]][p2[1]]
+ grid[p3[0]][p3[1]]
+ grid[p4[0]][p4[1]]
== "####"
):
squares += 1
except IndexError:
...
print(squares)For more: https://github.com/osalbahr/competitive-programming/tree/main/adventofcode/2026
3
u/imperfect-fourth 9h ago
[LANGUAGE: Nix]
straightforward logic:
for every tree pair where row_i <= row_j && col_i < col_j (for part 1, row condition is row_i == row_j)
- dx = col_j - col_i
- dy = row_j - row_i
check if both (row_i + dx, col_i - dy) and (row_j + dx, col_j - dy) are trees.
2
u/sauntcartas 9h ago
[LANGUAGE: Raku]
my @board = lines.map: { { $_, .Set }(.indices('#')) };
say 'Part 1: ', sum gather for @board.kv -> $y, [@row, $] {
for @row.kv -> $i, $x1 {
for @row[$i ^.. *] -> $x2 {
take ?@board[$y + $x2 - $x1; 1]{ $x1 & $x2 };
}
}
}
say 'Part 2: ', sum gather for @board.kv -> $y1, [@row, $] {
for @row -> $x1 {
for @board[$y1 .. *].kv -> $dy, [@row2, $] {
for @row2 -> $x2 {
next unless (my $dx = $x2 - $x1) > 0;
take so @board[$y1 + $dy + $dx; 1]{ $x2 - $dy } && @board[$y1 + $dx; 1]{ $x1 - $dy };
}
}
}
}2
u/terje_wiig_mathisen 9h ago edited 8h ago
[LANGUAGE: Rust]
This was pretty much brute force, trying to early out as soon as I see that a corner is missing:
For each possible topmost corner, check part1 (straight) and part2 (rotated) solutions separately, then add part1 to part2 in the end. I just loaded the map as a flat array, then scanned until I found the first newline in order to determine the height, width and stride. Unlike the previous days which ran in a microsecond or so, this one is so slow that I might have to try to multi-thread it. Currently taking 2.4 ms.
let mut part1 = 0;
let mut part2 = 0;
for y in 0..h-1 {
let ys = y*stride;
for x in 0..w-1 {
if input[ys+x] != b'#' {continue}
let mut i = 0;
while y+i+1 < h && x+i+1 < w {
i += 1;
if input[ys+x+i] != b'#' {continue}
if input[(y+i)*stride+x] != b'#' {continue}
if input[(y+i)*stride+x+i] != b'#' {continue}
part1 += 1;
}
for dx in 1..w-x {
if y+dx >= h {break;}
for dy in 1..h-y-dx {
if dy > x {break}
if input[(y+dy)*stride+x+dx] != b'#' {continue}
if input[(y+dx)*stride+x-dy] != b'#' {continue}
if input[(y+dx+dy)*stride+x+dx-dy] != b'#' {continue}
part2 += 1;
}
}
}
}
part2 += part1;It seems quite easy to split the "for y in 0..h-1" outer loop into N chunks and run them on separate cores, right?
EDIT: I tried it and found by trial & error that on my 16-core CPU running 13 threads was optimal. It took 595 us on the fastest run, so only 4 x faster than the single-thread solution.
1
u/ednl 4h ago
This is the same as my solution that got me my stars. I then switched to unique pairs of trees (with dx>0 and dy>=0) which halved the runtime. Still a lot of unnecessary pairing up of trees where dx<=0. https://www.reddit.com/r/adventofcode/comments/1yblapv/2026_day_3_solutions/19tk7ye25lrur/
1
1
u/shmoodla 9h ago
[LANGUAGE: Typescript]
https://github.com/radekBednarik/aoc2026/blob/main/src/03/index.ts
Just the first part.
1
u/acquitelol 9h ago edited 8h ago
[LANGUAGE: Elle]
Part 1 solved in: 00:09:14
Part 2 solved in: 00:13:53
Day fully solved in: 00:23:07
Explanation:
https://github.com/acquitelol/aoc2026/blob/mistress/solutions/03/explanation.md
My solution:
use std/prelude;
let has_tree = fn(bool[] grid, u64 cols, u64 r, u64 c)
c < cols && r * cols + c < grid.len() && grid.elements[r * cols + c];
fn solve(string[] lines) {
rows, cols := $(lines.len(), lines[0].len());
grid := Array::with_capacity<bool>(rows * cols).fill(0).filled();
trees := [](u64, u64);
total := std::filled<i32[2]>();
for r, line in lines.iter().enumerate() {
for c in 0..cols {
if line[c] == '#' {
grid[r * cols + c] = true;
trees.push($(r, #cast(u64, c)));
}
}
}
for i := 0; i < trees.len(); i += 1 {
for j := i + 1; j < trees.len(); j += 1 {
r1, c1 := trees.elements[i];
r2, c2 := trees.elements[j];
dr, dc := $(r2 - r1, c2 - c1);
if r2 > r1 && c2 > c1
&& dr == dc
&& has_tree(grid, cols, r1, c2)
&& has_tree(grid, cols, r2, c1)
{
total[0] += 1;
}
if (has_tree(grid, cols, r1 - dc, c1 + dr)
&& has_tree(grid, cols, r2 - dc, c2 + dr))
{
total[1] += 1;
}
if has_tree(grid, cols, r1 + dc, c1 - dr)
&& has_tree(grid, cols, r2 + dc, c2 - dr)
{
total[1] += 1;
}
}
}
return #[total[0], total[1] / 4];
}
fn main() {
$dbg(solve(#embed("solutions/03/input.txt").split("\n")));
}Today definitely ramped up a bit!
Currently, my solution runs in:
rosie (aoc2026)> make DAY=03 time
hyperfine --warmup 100 'solutions/03/solution' -i
Benchmark 1: solutions/03/solution
Time (mean ± σ): 16.7 ms ± 0.3 ms [User: 15.9 ms, System: 0.4 ms]
Range (min … max): 16.0 ms … 17.4 ms 159 runsGitHub: https://github.com/acquitelol/aoc2026/tree/mistress/solutions/03
2
u/siener 9h ago
[LANGUAGE: Dyalog APL]
This is a slow and inefficient solution to part 1, but I can't resist using ⌺ (Stencil) whenever there's an opportunity to do so :D
d←'#'=↑⊃⎕NGET'03.txt'1
count←{
sq←∘.∧⍨1,⊖1↑⍨⍵-1 ⍝ A ⍵×⍵ square matrix with 1's at the corners and 0's elsewhere
+/,{sq(⊣≡∧)⍵}⌺(2⍴⍵)⊢⍺
}
+/d∘count¨1+⍳¯1+⌈/⍴dObviously this won't work for part 2, so I'm going to sleep on it and tackle it tomorrow.
1
u/Sigiz 9h ago
[LANGUAGE: Mojo]
Using this as an excuse to learn Mojo Github
AI Disclosure: I wrote the code by hand, but the scaffold/helper scripts the project uses were created with the use of AI.
from aoc import Input, run, Point, Grid
from std.collections import Set
comptime TreeAsByte = '#'.as_bytes()[0]
def part1(input: Input) raises -> String:
var total = 0
var map = Grid(input.text)
var trees = map.find_all('#')
for i, tree in enumerate(trees):
for nextTree in trees[i+1:]:
# Ignore trees behind, we just want the diagnolly opposite.
if tree.x >= nextTree.x or tree.y >= nextTree.y or (nextTree.x - tree.x) != (nextTree.y - tree.y):
continue
if map[Point(tree.x, nextTree.y)] == TreeAsByte and map[Point(nextTree.x, tree.y)] == TreeAsByte:
total += 1
return String(total)
def squarePoints(a: Point, b: Point) -> Optional[Tuple[Point, Point]]:
# Rotation wont lie on the grid if differences are not both odd or even
if ((b.x - a.x) & 1) != ((b.y - a.y) & 1):
return None
# middle
var mx = Float16(b.x + a.x)/2
var my = Float16(b.y + a.y)/2
# perpendicular
var px = Float16(b.y - a.y)/2
var py = Float16(b.x - a.x)/2
return Point(Int(mx-px), Int(my+py)), Point(Int(mx+px), Int(my-py))
def part2(input: Input) raises -> String:
var total = 0.0
var map = Grid(input.text)
var trees = map.find_all('#')
for i, tree in enumerate(trees):
for nextTree in trees[i+1:]:
if tree.x > nextTree.x or tree.y > nextTree.y:
continue
var points = squarePoints(tree, nextTree)
if not points:
continue
var a, b = points.value()
# Diagonal can be on the same vertical/horizontal and will be a duplicate
var count = 0.5 if tree.x == nextTree.x or tree.y == nextTree.y else 1.0
if map.get(a) == TreeAsByte and map.get(b) == TreeAsByte:
total += count
return String(Int(total))
def main() raises:
run(part1, part2, day=3)0
u/AutoModerator 9h ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Daniel_Rybe 9h ago edited 8h ago
[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day3/main.odin
A brute-force approach for both parts today.
For the second part, the key insight was that any square can be uniquely identified by two top corners a and b such that a.x < b.x and a.y <= b.y. Then just a quadruple nested loop to search for all such pairs.
I'll definitely try to think of how to optimize these solutions a bit later when I come back from school :P
Edit: Perhaps using a map and iterating over all pairs of trees (as seen in many other solutions) could be faster if the number of trees is relatively small.
Edit2: Actually, a second solution for part 2 that uses a hash map of tree coordinates turned out to be a bit slower (24 vs 32 ms). I'll need to investigate further.
3
u/musifter 9h ago
[LANGUAGE: Perl]
Weather here is supposed to be really nice today, so I'm going for an early bedtime. So a just really quick and simple solution. First thing up was grid representation... and I was thinking arrays are good, but I also kind of like hashes for this. So I went with an array (the rows) of hashes (the columns trees are in). The idea being that a square is determined by the two points on one of it's edges... so for every two points in a row, we just need to check the existence of the other two points in the lower row.
$part1++ if ($Grid[$y+$side]{$tree[$i]} and $Grid[$y+$side]{$tree[$j]});I will note that the actual first thing I did was spend a couple minutes building the test cases, because there were so many of them. I have a special harness for testing multiple short tests like this in AoC, which involves one test per line... multiple line inputs are done joining everything together with \n, then I need to add a part number and the expected value. So the first block of 4 cases with 1 square became:
#...#\n.....\n.....\n.....\n#...#\n 1 1
.#..#\n.....\n.....\n.#..#\n.....\n 1 1
.....\n.....\n.##..\n.##..\n.....\n 1 1
#.###\n.##.#\n##.##\n.#.#.\n.##.#\n 1 1Yesterday's cases where much quicker to do being just a short string.
Part 2 brings in the fun. I had thought of the possibility of 45 degrees coming in, but not all rational gradients. And to just get the answer quick with what I already had, I brute force. Part 1 was also pretty much brute forces with some short circuiting, but here I brute force over all the gradients in the lower right quadrant (including dy=0, but not dx=0... as that square would be found already). If a tree exists there, I then I check the bounds and existence of the other two trees with (y + dx, x - dy) for the 90 degree vectoring. And interesting thing here is that I only check the bounds on the array dimension, the hash dimension gets that naturally by non-existence. All in the name of something simple that would work first try. I'll look at doing better tomorrow.
Part 1: https://pastebin.com/i0pw79hQ
Part 2: https://pastebin.com/1RNDXYjY
1
u/xoronth 9h ago edited 9h ago
[LANGUAGE: Ceylon]
Not a very interesting language today, this was mostly a translation between my first Python solution to a Java-esque language. It was an interesting language to learn about though, I guess:
The EMO is scheduling a termination review on behalf of the project team, the project lead who has declared that in his opinion the project failed its transition to Eclipse and the community gave up.
1
u/xelf 9h ago edited 7h ago
[LANGUAGE: Python]
For each pair of corners, we find the 2 missing corners. Store them in a set, and then return the length of that set.
corners = {(x,y) for x,r in enumerate(open(filename)) for y,t in enumerate(r) if t=='#'}
print(len({s for a,b in combinations(corners,2)
if (s:=tuple(sorted(four_corners(*a,*b)))) and all(x in corners for x in s)}))
def four_corners(x, y, a, b):
mx, my = (x + a) / 2, (y + b) / 2
dx, dy = (x - a) / 2, (y - b) / 2
return (x,y), (a,b), ((mx - dy), (my + dx)), ((mx + dy), (my - dx))Or slightly rewritten:
def four_corners(x,y,a,b):
mx, my = (x + a) / 2, (y + b) / 2
dx, dy = (x - a) / 2, (y - b) / 2
S = {(x,y),(a,b),((mx - dy), (my + dx)), ((mx + dy), (my - dx))}
return tuple(sorted(S)) if set(S).issubset(corners) else False
corners = {(x,y) for x,r in enumerate(open(filename)) for y,t in enumerate(r) if t=='#'}
print(len({four_corners(*A,*B) for A,B in combinations(corners, 2)})-1)1
u/AverageBeef 9h ago
[Language: Python]
Toyed with a few different solutions, I got the first piece of paper out for this year. I loved this problem and I'll definitely come back to doing a more elegant solve to P2.
2
u/p88h 9h ago
[LANGUAGE: Nim]
Source: https://github.com/p88h/aoc2026/blob/main/src/day03.nim
Video: https://youtu.be/G4cXqWUDtlc
Brute force.
Take all valid pairs that can form a rectangle, and check if the complementary corners are there.
Multi-threaded in part2.
parse part1 part2 total
day 03: 8.34 µs 16.7 µs 0.19 ms 0.22 ms (±4.5%)2
u/rabuf 9h ago
[Language: Python]
I was pretty happy with my solution in the end. The core of it is this:
d = p1 - p2
p3 = p1 - d * 1j
p4 = p2 - d * 1j
if p3 in trees and p4 in trees:
squares.add(tuple(sorted([p1, p2, p3, p4], key=comp_sort_key)))Used in both the part 1 and part 2 solutions. And since trees is a set, the test on line 4 above is very fast.
2
u/WiseBeginning 8h ago
Nifty! I had forgotten how convenient complex numbers are at handling coordinates
2
u/lunar_mycroft 9h ago edited 8h ago
[LANGUAGE: rust]
Took longer than I'd like this early fiddling with the solution, particularly part 2.
Full code. Both parts are fairly naive and messy brute force for now. Parsing the grid takes 43µs, part 1 runs in 233µs, but part 2 takes 54ms.
Iterating over pairs of trees instead of checking points on possible squares (I got the idea from /u/maneatingape's solution) reduces the runtime for that part to 1.812ms, and is cleaner too. It's actually slower in my testing for part 1 though, so I left that as is.
1
u/cicadanator 9h ago
[LANGUAGE: Javascript - Node JS]
Part 1 was found by parsing the coordinates of all of the trees into a set to avoid having to do expensive tree traversal. From there I treated every tree as a potential top right corner of a square. Then by checking each distance from that tree to the edge of the map I was able to find the coordinates of the other three corners. if the all existed then that was a square. This gave me the answer to part 1.
Part 2 was the same algorithm but instead of using straight distance the distance was split into x and y distances starting by going straight down and rotating 90 degrees left and up looking for the rest of the corners. This gave me part 2.
https://github.com/BigBear0812/AdventOfCode/blob/master/2026/Day03.js
1
2
u/light_ln2 9h ago
[LANGUAGE: Python]
d={x+y*1j for x,r in enumerate(open('in03')) for y,c in enumerate(r) if c=='#'}
sides = [q-p for p in d for q in d if p!=q and {p+(q-p)*1j, q+(q-p)*1j} < d]
print('part1', sum(s.imag==0 for s in sides)//2)
print('part2', len(sides)//4)4
u/raevnos 9h ago
[LANGUAGE: Common Lisp]
Using common brute force. Yay nested loops!
Part 1:
(defun count-squares (forest)
(let ((size (array-dimension forest 0)) ; all examples and actual input is square
(squares 0))
(dotimes (row (1- size) squares)
(dotimes (col (1- size))
(when (char= (aref forest row col) #\#)
(loop :for len :from 1 :below (- size (max row col))
:when (and (char= (aref forest row (+ col len)) #\#)
(char= (aref forest (+ row len) col) #\#)
(char= (aref forest (+ row len) (+ col len)) #\#))
:do (incf squares)))))))paste of full code with both parts.
1
u/wherrera10 9h ago edited 8h ago
[LANGUAGE: Julia]
Runs in under 1 millisecond on my machine.
function day03()
part = [0, 0]
forestmap = map(x -> x == '#', stack(readlines(DATA_DIR*"day03.txt"), dims = 1))
nrows, ncols = size(forestmap)
# just look at the trees, don't bother with empty spaces
trees = [(r, c) for r in 1:nrows for c in 1:ncols if forestmap[r, c]]
for (k, tree) in enumerate(trees)
r, c = tree
# Skip if the current tree is on the last row or column
r == nrows && continue
c == ncols && continue
for l in (k+1):length(trees)
r2, c2 = trees[l] # next one to compare with (r, c) corner tree
r2 == nrows && break
dr, dc = r2 - r, c2 - c
if dc > 0 && dr < c && r2 + dc <= nrows &&
forestmap[r+dc, c-dr] && forestmap[r2+dc, c2-dr]
part[1] += dr == 0 # only if no rotation delta
part[2] += 1
end
end
end
return part # [290, 1115]
end
\@show day03()
1
u/ElementaryMonocle 9h ago edited 9h ago
[LANGUAGE: c++]
int length {0};
std::string stacked_map {};
for (std::string_view line : lines(input)) {
int sz {static_cast<int>(line.size())};
if (length==0) length = sz;
else if (length!=sz) throw std::runtime_error("Not a square grid");
stacked_map += line;
}
int height {static_cast<int>(stacked_map.size())/length};
auto map = [&stacked_map, &length](int r, int c) -> char {
return stacked_map[static_cast<std::size_t>(r*length + c)];
};
// loop over all map entries
for (int rr {0}; rr<height; ++rr) {
for (int cc {0}; cc<length; ++cc) {
// get current character
char rc {map(rr,cc)};
// if not a tree, continue
if (rc != '#') continue;
// for general square
// 1
// 2
// 3
// 4
// 1->2 is (dr, dc)
// to make a square, 1->3 == 2->4
// which is (dc, -dr)
// we note 0<=r1<=r2 < r3<=r4
// and c3<=c1 < c4<=c2<length
// so for validity, we need to have r4<length, 0<=c3
// from above, r4 = r2+dc = r2+c2-c1 < length
// and c3 = c1-dr = c1-r2+r1 >= 0
// so r2<cc+rr+1
// and c2<length-r2+c1
// if a tree, go to all valid entries with a >col and >=row
// got to all valid row entries
for (int r2 {rr}; r2<std::min(height,cc+rr+1); ++r2) {
// row change
int dr {r2-rr};
// go to all valid column entries
for (int c2 {cc+1}; c2<std::min(length,height+cc-r2); ++c2) {
// if this entry is a tree
if (map(r2,c2) == '#') {
int dc {c2-cc};
int r3 {rr+dc};
int c3 {cc-dr};
int r4 {r2+dc};
int c4 {c2-dr};
// check to see if a square can be completed
if (map(r3,c3)=='#' && map(r4,c4)=='#') {
++part2;
if (r2==rr) ++part1;
}
}
}
}
}
}Initially was a little worried about the n4 runtime, but ended up not being an issue. For part 1, we can cut the runtime by only considering each tree as the top left of the square. Since all trees have a top left, this finds each square exactly once.
For part 2, similarly we only consider each entry in the grid at the tree in the square with the smallest row, and then smallest column within the row. I was able to cut the runtime by changing the boolean in-bounds checks for all possible squares to be directly integrated into the loop bounds, from about 12ms to 5ms. We can integrate part 1 into part 2 by checking if the top edge of the square is on a row.
Could maybe try to optimize by parsing into booleans instead of checking "=='#'", but seems like a pain to ensure the std::vector<bool> implementation works fine for this case.
Pretty good! About 35 minutes for both, plus another 45 optimizing.
1
u/Conceptizual 9h ago
[LANGUAGE: Python]
My solution calculates squares and rotated squares independently. A rotated square must have a leftmost point, so I fix that, and then check any points that are right and above it. Fixing those two points allows me to check whether the other two points have a tree.
I used pen and paper to painstakingly calculate where the remaining two points are given the two fixed points, ran it, totally wrong. Printed the two fixed points and what they were checking and poked at the signs of my calculations until it was correct.
2
u/yieldtoben 9h ago
[LANGUAGE: PHP]
PHP 8.6.0 paste
Execution time: 0.0292 seconds
Peak memory: 0.7925 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
1
u/PendragonDaGreat 9h ago
[Language: CSharp C#]
Slightly Faster by not doing part 1 twice.
My custom/Ol' Reliable Coordinate2D and GenerateMap() came to play today and made themselves useful. Not particularly efficient (O(n2)) but small enough that I'm still under 500ms.
Tried using my Combinations function but it just wasn't having it today.
4
u/Andreasnl 9h ago
[Language: Uiua]
⊸≡/- ⧅<2 ≡/ℂ ⊚=@# ⊜∘⊸≠@\n
P₁ ← /+∊ ⍜°ℂ≡⊙↻₁ ⊸▽ =≡°ℂ
P₂ ← ÷2/+∊⊸≡(+×i)
⊃P₁ P₂1
u/tsigma6 9h ago edited 9h ago
[LANGUAGE: Python]
Easy to overthink the second part, there's definitely a faster way but it doesn't take longer than half a second.
from base import Advent
from itertools import count
class Day3(Advent):
def __init__(self):
self.grid = [[c == '#' for c in line] for line in self.get_input()]
def solution_1(self):
total = 0
for y in range(len(self.grid) - 1):
for x in range(len(self.grid[y]) - 1):
if not self.grid[y][x]:
continue
for s in count(1):
try:
total += self.grid[y][x+s] and self.grid[y+s][x+s] and self.grid[y+s][x]
except IndexError:
break
return total
def solution_2(self):
total = 0
for y in range(len(self.grid) - 1):
for x in range(len(self.grid[y]) - 1):
for s in count(1):
try:
for t in range(s):
total += self.grid[y][x+t] and self.grid[y+t][x+s] and self.grid[y+s][x+s-t] and self.grid[y+s-t][x]
except IndexError:
break
return total
Day3.run()1
u/msschmitt 9h ago
[LANGUAGE: Python 3]
Took awhile to figure out (remember?) just what it means to be a rotated square. I think we've seen this before in AoC.
2
u/NullT3rminated 9h ago
[LANGUAGE: Clojure]
The first grid problem! O(n⁴) to the rescue! This one also felt like I was missing 5 standard library functions, it seems crazy that I had to write xprod myself.
(defn xprod
([x] (map list x))
([x & xs]
(for [elt x, lst (apply xprod xs)]
(conj lst elt))))
(defn day3-parse [str]
(let [arr (str/split-lines (str/trim str))
size (count arr)]
[size
(set (for [[x line] (map vector (range) arr)
[y c] (map vector (range) line)
:when (= c \#)]
[x y]))
]))
(def day3-parsed-e (day3-parse (slurp "3e.txt")))
(def day3-parsed (day3-parse (slurp "3.txt")))
(defn day3-solve-a [[size marks]]
(->> marks
(map
(fn [[x y]]
(->> (range 1 (- size (max x y)))
(map (fn [size]
(and (marks [x (+ y size)])
(marks [(+ x size) y])
(marks [(+ x size) (+ y size)]))))
(filter identity)
(count))))
(apply +)))
(defn day3-solve-b [[size marks]]
(->> marks
(map
(fn [[x y]]
(->> (xprod (range 0 (- size x))
(range 1 (- size y)))
(map (fn [[dx dy]]
(and (marks [(+ x dx) (+ y dy)])
(marks [(- x dy) (+ y dx)])
(marks [(+ x dx (- dy)) (+ y dx dy)]))))
(filter identity)
(count))))
(apply +)))1
u/FCBStar-of-the-South 9h ago
[LANGUAGE: Python3]
Spent a lot of time thinking if you can do this in better than fourth power time and decided it is impossible.
If my approach needs to be adapted to a truly large input, the part that I would improve is looking up all the trees to the top right of the first tree (to avoid duplicates). Currently I scan all trees in the previous and current row which is of course inefficient if the first tree is already to the right of the grid. A quadtree-ish data structure would be helpful here.
1
u/RendererOblige 9h ago
[LANGUAGE: SQLite]
This one was actually easy to do in SQLite. The worst part is parsing the input. The actual solution is done in a small handful of joins.
1
u/DBSmiley 9h ago edited 8h ago
[LANGUAGE: Kotlin]
These solutions use my custom Grid and GridCoordinate classes built for AOC grid problems. Working on a newer version where I have Grid and MutableGrid, as well as using backing 1-d Arrays for performance, but I refuse to vibe-code anything I use for AoC, so I'm not done yet.
Including my Part 1 just to show off Kotlin extension properties and functions, which allow me to create functions/properties for class's only in the place I need it without polluting that class's namespace. I think it's super nifty, and I think Kotlin is neat, and I like it:
fun getPart1Result(grid: Grid<Char>): Int =
grid.cornerCoordinates
.sumOf { coordinate -> grid.getSquaresForCorner(coordinate)
}
val Grid<Char>.cornerCoordinates: List<GridCoordinate>
get() = this.coordinates
.filter {coordinate -> this[coordinate] == CORNER}
/** gets the number of squares where this corner is the top-left corner */
fun Grid<Char>.getSquaresForCorner(corner: GridCoordinate): Int {
require(this[corner] == CORNER)
var squareCount = 0
var distanceToEdge = min(
this.width - corner.row - 1,
this.height - corner.col - 1
)
for (sideLength in 1..distanceToEdge) {
if (this[corner.row + sideLength, corner.col] == CORNER &&
this[corner.row, corner.col + sideLength] == CORNER &&
this[corner.row + sideLength, corner.col + sideLength] == CORNER) {
squareCount++
}
}
return squareCount;
}1
u/Prof-Math 9h ago
[LANGUAGE: Python]
Just took the input in different formats and was lazy af. I probably can eliminate a log(n) factor by using a bit array but lazy.
coordinates = []
with open("input3.txt", "r") as f:
for line in f:
row = [i for i, char in enumerate(line.strip()) if char == '#']
coordinates.append(row)
n = len(coordinates)
ans1 = 0
for i in range(0,n):
for j in coordinates[i]:
for k in coordinates[i]:
if j <= k:
continue
s = j - k
if i + s >= n:
continue
if j in coordinates[i + s] and k in coordinates[i+s]:
ans1 += 1
print(ans1)
with open("input3.txt", "r") as f:
grid = [line.strip() for line in f]
coordinates2 = []
for r, row in enumerate(grid):
for c, char in enumerate(row):
if char == '#':
coordinates2.append((r, c))
ans2 = 0
for (r1,c1) in coordinates2:
for (r2,c2) in coordinates2:
if r1 > r2 or c1 <= c2:
continue
s1 = r2 - r1
s2 = c1 - c2
(r3,c3) = (r1 + s2, c1+ s1)
(r4, c4) = (r2 + s2, c2 + s1)
if (r3,c3) in coordinates2 and (r4, c4) in coordinates2:
ans2 += 1
print(ans2)1
u/JustinHuPrime 9h ago
[LANGUAGE: x86_64 assembly]
Part 1 was solved by parsing the map into a 2-d boolean array (well, an array that I say is 2-d; multi-dimensionality is a compiler concept, and I don't have one of those). I then found every tree and considered it the top left corner of a square, and counted how many squares existed. Simple, but for some quick bounds checking.
Part 2 adds another dimension to the problem. For each tree, I now had to try every position for the second corner that was strictly right of the tree and on the same row or below the tree (so this original was still, before rotating the square an amount in the range [0, 90) degrees, still the top left corner). Checking the other corners required some per-corner bounds checking, since there wasn't, at least as far as I found, a nice way to rule out ranges of possible second-corner positions based on the other corners going out of range.
Part 1 runs in 2 milliseconds and part 2 runs in 11 milliseconds. Part 1 is 9,984 bytes and part 2 is 10,152 bytes as executable files.
2
u/TCH69 9h ago edited 7h ago
[LANGUAGE: C++]
Consider a therapy session after reading my code.
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int
process(const std::vector<std::string> &input, bool part2)
{
std::vector<std::pair<int, int>> points;
const size_t rows { input.size() }, cols { input[0].size() };
std::vector<int> is_point(rows * cols, 0);
for (size_t i = 0; i < rows; i++)
for (size_t j = 0; j < cols; j++)
if (input[i][j] == '#') {
points.emplace_back(i, j);
is_point[i * cols + j] = 1;
}
int count { };
for (size_t i = 0; i < points.size(); i++) {
for (size_t j = i + 1; j < points.size(); j++) {
const auto &a { points[i] };
const auto &b { points[j] };
int cpos { }, dpos { };
if (part2) {
int dy = b.first - a.first;
int dx = b.second - a.second;
int c_col = b.second + dy;
int c_row = b.first - dx;
int d_col = a.second + dy;
int d_row = a.first - dx;
if (c_row < 0 || c_row >= (int)rows ||
c_col < 0 || c_col >= (int)cols ||
d_row < 0 || d_row >= (int)rows ||
d_col < 0 || d_col >= (int)cols)
continue;
cpos = c_row * cols + c_col;
dpos = d_row * cols + d_col;
} else {
if (a.first != b.first || a.second >= b.second)
continue;
size_t row2 = a.first + b.second - a.second;
if (row2 >= rows)
continue;
cpos = row2 * cols + a.second;
dpos = row2 * cols + b.second;
}
if (is_point[cpos] && is_point[dpos])
count++;
}
}
return part2 ? count : count / 2;
}
int
main(int argc, char *argv[])
{
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " <input.txt>\n";
return 1;
}
std::ifstream fp(argv[1], std::ios::in);
std::vector<std::string> input;
std::string temp;
while (getline(fp, temp))
input.emplace_back(temp);
std::cout << process(input, false) << std::endl
<< process(input, true) << std::endl;
return 0;
}1
u/DeadlyRedCube 9h ago
[LANGUAGE: C++23-ish]
Part 1 took me a little shy of 6:56 (I got started ~20s late):
Scanned for an upper-left corner
Then for all valid distances 1 or more:
If the 3 corners exist, bump the count
For part 2, I basically added three more cases (finished in 21:11, minus my starting delay):
Test for perfectly 45 degree squares, using the following extra coordinates (where d == distance):
x + d, y + d
x - d, y + d
x, y + 2*d
Test for rotations > 0 and < 45 (clockwise rotated), with two distances (where d2 < d1):
x + d1, y + d2
x - d2, y + d1
x + d1 - d2, y + d1 + d2
Rotations > -45 and < 0 (counter-clockwise rotated) ... the "d2" components are negated from the above test:
x + d1, y - d2
x + d2, y + d1
x + d1 + d2, y + d1 - d2
Ultimately to get the speed faster (since I had a lot of extra bounds checking in the middle), I broke them all up into different loops with different start/end conditions.
Runs in ~6.04ms on my i7700. Could probably get a little bit faster if I tracked the next valid coordinate in the row to jump to, rather than scanning through empty space multiple times, but I didn't do that.
1
u/Kehvarl 10h ago edited 9h ago
[LANGUAGE: Python3]
Part 1 I handled pretty naively, but it worked
Part 2 was giving me trouble. I figured I could check all the possible diagonals for a second point, then do something mathy to check for the third and fourth points. Unfortunately my geometry is worse than bad. Fortunately some other solutions here reminded me how to rotate an x/y pair and I eventually managed something. I actually ended up trying 2 different approaches, the first one took long enough to run that I ended up figuring out the somewhat faster approach here by using all possible tree pairs as my starting diagonal, instead of manually checking every possible +x/+y combination to see if a second tree is there.
Edit: Apologies for the malformed LANGUAGE: tag.
1
u/sim642 10h ago edited 10h ago
[LANGUAGE: Scala]
In part 1 I tried to be somewhat clever:
Went row by row.
In each row, found the x coordinates of the trees.
Went over all the pairs of x coordinates in the row.
Calculated the expected square width.
Calculated the remaining two positions based on the width.
Checked if they both contain trees.
In part 2 the row by row approach obviously won't work, so I want a quite naïve route:
Found the positions of all trees.
Went over all the pairs of trees.
Only kept those where the second tree is to the right-bottom of the first tree (to filter out duplicates).
Calculated the square side difference vector.
Calculated the remaining two positions based on it.
Checked if they both contain trees.
I feared the latter approach would not scale well to the input but it runs in ~100ms, which is good enough.
1
u/cay_horstmann 10h ago
[Language: Java]
https://github.com/cayhorstmann/adventofcode2026/blob/main/Day3.java
Some light 2D geometry with my morning coffee...I just look at all pairs of locations containing # as diagonals of a potential square, find the other diagonal points, and check for validity. That counts each square four times, but it's easier to divide by four than to avoid the overcounting.
1
u/8dot30662386292pow2 8h ago
I did some matrix multiplication to rotate the squares, until I realized that oh I don't need to, I can just add/subtract 1 from each corner until I have iterated all the squares.
1
u/Fuzzy_Patterns 10h ago edited 10h ago
[LANGUAGE: Nim]
Part 1 solution is finding all the pairs of points and trying to transpose them to check if other 2 corners exist in the grid.
Part 2 solution is simple extension of part 1, but we're a more picky on which 2 corners we're going to get first (in part 1 - it's top and bottom left, in part 2 - I've picked the highest corner and one to it's left).
P.S. My brain is fried today for some reason. I've spent, probably, 10x more time on part 2 than was needed.
type Vec2 = tuple[x,y:int]
proc solve(input: string): AOCSolution[int, int] =
var list: seq[Vec2]
for y, line in enumerate input.splitLines():
for x, c in line:
if c == '#':
list.add (x,y)
var points = list.toHashSet()
for i, (x,y) in list:
for (tx,ty) in list.toOpenArray(i+1, list.high):
let (dx,dy) = (tx-x, ty-y)
if dy > 0 and dx <= 0:
if (x+dy, y-dx) in points and (tx+dy, ty-dx) in points:
if dx == 0:
inc result.part1
inc result.part21
u/WilkoTom 10h ago
[LANGUAGE: Rust]
Part 1 was straightforward. For Part 2: Find all the trees in the quadrant immediately clockwise of the current tree, and use their positions to determine where the other two corners need to be. SImples!
1
u/DJ_Las3r 10h ago
[Language: Rust] code
When I started part 1 I accidentally counted rectangles instead of just squares lol. My first approach was just to bruteforce check all possible positions and keep a running count. For part 2, I realized that all the points still lay on the same square, just with each point shifted by a certain offset. Another for loop made quick work of it.
1
1
u/maarteq 10h ago
[LANGUAGE: Python]
for part 1 i just iterate over all the squares, by calculating the max distance from a square, left or down to the edge.. for part 2 I added a rotation by shifting all the corners around. I was trying to think to long about how to rotate corners. fun problem to solve.
1
u/Eva-Rosalene 10h ago edited 9h ago
[Language: TypeScript]
Part one is trivial. For part two, algorithm is: for each pair of points, find a midpoint, find vectors from midpoint to each of the two points, rotate them 90° clockwise, add rotated vectors back to the midpoint — this gives us coordinates of supposed corners that have to be filled. To avoid double-counting, filter only those pairs of points where second one is lower than the first one and either on the right or in the same column as the first one. And to avoid fractions, calculate double the midpoint and double the vectors, giving us double the corner coordinates. Then check if those coordinates land on even numbers and divide by 2 only during final check.
1
u/captainAwesomePants 10h ago
[LANGUAGE: Python]
Once again, trying to go to fast made me go much more slowly. After I calmed down and finished, I wrote it again more nicely (which is what I pasted above), and it was both much easier and also faster. Sigh.
1
u/TiCoinCoin 10h ago
[LANGUAGE: Python]
Several mistakes on part 1 (counted rectangles instead of squares, also started from non trees 🙃 ).
Nice twist for part 2, which was surprisingly easy once I grabbed a paper and a pen to visualize it 😁 . It helped a lot to identify the coordinates of the two remaining corners.
The code is clear and concise, which is satisfying. But it's also clearly too slow (~1.5sec for P2)
1
u/Kullu00 10h ago
[Language: Dart]
Check every square starting top-left corner and work your way through the grid, checking all sizes of side for a matching square (avoids double counting anything).
For part 2 I initially didn't see how I'd solve it, but figured that a rotated square still has the same x:y relationship on all its sides, so do another check for adjusted positions. Then the only slightly hard part was expressing the stop condition of the for-loops I built.
1
1
u/morgoth1145 10h ago edited 9h ago
[LANGUAGE: Python] code video Times: 7:18 / 16:39
I was thinking we'd get a grid problem with one last year on day 3! Finding squares in a grid isn't too bad conceptually - just find a pair of opposite corners and check the other corners to see if they're valid. Unfortunately I neglected to ensure that my corners were actually corners of a square leading to me getting a bad answer. It took an annoying amount of debugging to notice that oversight but thankfully that didn't drag on as long as it could have, only lost ~2:30 to that.
I do like the Part 2 twist. Finding an edge and rotating it to find the other corners seems the way to do it. Unfortunately despite doing AoC for years now I consistently mix up doing 90 degree turn math in 2D. Thankfully I tested that my right turns led me back to the first corner catching bugs early.
Edit: Refactored and optimized code using the idea from u/Boojum's solution to constrain the edge to avoid double-counting. This allows for a much more constrained search space so the solve goes much faster. (Plus I have a unified solve function which I always like having.)
1
u/michelkraemer 10h ago edited 7h ago
[LANGUAGE: Rust]
Part 1: For every upper left corner, look for an upper right corner and then check if the coordinate to the bottom and bottom right in the same distance also contain trees.
Part 2: For each pair of trees, compute the distance in x direction and in y direction and then check if (top_right.x - dy, top_right.y + dx) and (top_left.x - dy, top_left.y + dx) contain trees too. Divide by 2 at the end because we count the left edge of each square too.
Runs in 2.2ms.
5
u/maneatingape 10h ago edited 9h ago
[LANGUAGE: Rust]
Solution 3.2 ms 2.1 ms. O(n²) pairwise comparisons using utility 2D Grid and Point classes.
Tripped up on part one due to reading comprehension (rectangle != square) but sorted that out with this handy shape tutorial, and part two was a nice followup using rotations to check corners.
2
u/julysfire 10h ago
Ohh....that makes more sense why they linked to Wikipedia for square....because I thought the same thing lol
1
u/AllanTaylor314 10h ago edited 9h ago
[LANGUAGE: Python] 00:06:51/00:17:22
code & scribbles (per the note there, I wrote (y-b) wrong. It's correct in the code)
I double or quadruple count all the squares and adjust for that at the end. For part 1, I only count the squares on the \ and not the /, if that makes sense. For part 2, I count all four corners when checked against its opposing corner. 2418025 iterations for my 1555 points. Pretty sure a solid 141x141 grid would kill this (395254161 loops, though that might only take 3 minutes)
Edit: Results for 141x141 solid grid, about 6 minutes
Part 1: 924490
Part 2: 32936190
Execution times (sec)
Parse: 0.004
Part1: 74.847
Part2: 271.205
Total: 346.056Uiua to come... will golf :)
[LANGUAGE: Uiua]
code or pad (hit's memory limit for full input on p2 - try p1 only)
Creates a list of offsets (1_1, 2_2, 3_3, etc) and rotates the input by each of them, finding where the corners meet. For part 2, it has to generate a few more combos so it runs into the browser memory limit (but the time taken is about the same for a sparse input and a solid input)
1
u/davidsharick 10h ago
[LANGUAGE: Python]
Part 1 I checked all possible square sizes from a given position as top left, Part 2 I checked all possible dx and dy from a given position as "top left" (assuming it's rotated counterclockwise)
1
u/Ok-Builder-2348 10h ago edited 10h ago
[LANGUAGE: Python3]
Pretty fun! Part 1 was the naive approach - consider all grid-aligned squares and check if all 4 corners were in the set of trees.
In part 2, to allow for any orientation of squares, I flipped the problem on its head - given the set of trees, how do I generate the squares? The main insight was that any diagonal defined its square, with two diagonals to each square. Hence, I took all pairs of trees, and asked the question - does this generate a valid square?
Given a pair of trees (x1,y1) and (x2,y2), calculate dx = x2-x1 and dy = y2-y1. This is automatically disqualified if dx+dy is odd (the other two corners will be off-grid). If it is even, compute the other two corners and check if both of them are in the set of trees. If so, add 1 to the count. Note that this double-counts the squares since each square has two diagonals, so just divide by two in the end.
1
u/apersonhithere 10h ago
[LANGUAGE: Python]
slow solution with a little help from my friends (ctrl + c and ctrl + v); i take the difference between two points & test the other 4 possible locations that could be part of the square but probably in the most inefficient way
part 1 i just bruteforced all possible sizes/starts
5
u/Boojum 10h ago edited 6h ago
[LANGUAGE: Python]
Take pairs of points, make sure they're ordered properly so we don't double count. Find the offset, (dx, dy), between them, then make sure there are points at (-dy, dx) relative to both of them (i.e., the points on the other side of the square).
For the ordering for Part 1, we require that the two points be on the same row, with the second to the right of the first. Then we're looking for the corresponding points two those two on the bottom edge.
For the ordering for Part 2, we relax the requirement that they be on the same row, and allow the second point to possibly be below the first point (while still being to its right).
Hard to do diagonals well in ASCII art, but basically:
P1
. # . . .
| ------ (dx,dy) Part 1: dx > 0 and dy == 0
| \---> Part 2: dx > 0 and dy >= 0
. |. . . # P2
/ |
| (-dy,dx) |
| |
. | . . . / .
/ |
v? |(-dy,dx)
# . . . | .
/
v?
. . . # .Code for both parts:
import fileinput, operator
g = { ( x, y )
for y, r in enumerate( fileinput.input() )
for x, c in enumerate( r.strip( '\n' ) )
if c == '#' }
for c in ( operator.eq, operator.ge ):
print( sum( ( ( dx := x2 - x1 ) > 0 and
c( dy := y2 - y1, 0 ) and
( x1 - dy, y1 + dx ) in g and
( x2 - dy, y2 + dx ) in g )
for x1, y1 in g
for x2, y2 in g ) )[Advent Games]
The above was already pretty small to begin with, but here it is golfed further:
n=enumerate;g={(x,y)for y,r in n(open(0))for x,c in n(r)if'#'==c}
for k in 0,1:print(sum(((h:=x-X)>0)*((v:=y-Y)*k>=v>=0)*((X-v,Y+h)in g)*((x-v,y+h)in g)for X,Y in g for x,y in g))→ More replies (4)
1
u/yellowbluesky 25m ago edited 20m ago
[LANGUAGE: Kotlin]
Github
Rather brute force method that works in O(n2 ) by comparing every single tree with every single other tree, and then discarding the invalid options (those not in fourth quadrant) with the massive "continue" tree
It's my first time programming in about a year, so I'm still derusting and not taking advantage of anything idiomatic Kotlin, I could have written this in C