2026/day3: improve pairwise implementation of part2, it now performs better than brute
This commit is contained in:
1 file changed
+23
-19
+23
-19
@@ -59,27 +59,31 @@ fn rotated_offsets(initial: Coord2d) -> [Coord2d; 3] {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Thought this might be faster, but it is _way_ slower. I think it requires smarter culling of combinations which will
|
// Generate the other two corners of a square given the top left and top right coordinates, in clockwise order
|
||||||
// get removed later as already found. I tried a simple cull which undercounted and still took 40x longer than the
|
fn other_two(a: &Coord2d, b: &Coord2d) -> [Coord2d; 2] {
|
||||||
// 'bruteforce' approach.
|
let ofs = b - a;
|
||||||
|
[
|
||||||
|
Coord2d {
|
||||||
|
x: a.x + (ofs.x - ofs.y),
|
||||||
|
y: a.y + (ofs.x + ofs.y),
|
||||||
|
},
|
||||||
|
Coord2d {
|
||||||
|
x: a.x - ofs.y,
|
||||||
|
y: a.y + ofs.x,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
#[aoc(day3, part2, Pairwise)]
|
#[aoc(day3, part2, Pairwise)]
|
||||||
fn part2_pairwise(input: &Grid<u8>) -> u64 {
|
fn part2_pairwise(input: &Grid<u8>) -> u64 {
|
||||||
let mut combos: BTreeSet<_> = input.find_all(&b'#').tuple_combinations::<(_, _)>().collect();
|
let trees: Vec<Coord2d> = input.find_all(&b'#').collect();
|
||||||
let mut squares = 0;
|
return trees
|
||||||
while let Some((a, b)) = combos.iter().next().copied() {
|
.iter()
|
||||||
let ofs = (b.x - a.x, b.y - a.y);
|
.tuple_combinations::<(_, _)>()
|
||||||
let other_corners = rotated_offsets(ofs.to_coord()).map(|ofs| a + &ofs);
|
.filter(|(a, b)| (*b - *a).x >= 0 && (*b - *a).y > 0)
|
||||||
for pair in [a, other_corners[0], other_corners[1], other_corners[2]]
|
.map(|(a, b)| other_two(&a, &b))
|
||||||
.iter()
|
.filter(|corners| corners.iter().all(|pos| input.get(&pos) == Some(&b'#')))
|
||||||
.permutations(2)
|
.count() as u64;
|
||||||
{
|
|
||||||
combos.remove(&(*pair[0], *pair[1]));
|
|
||||||
}
|
|
||||||
if other_corners.iter().all(|pos| input.get(&pos) == Some(&b'#')) {
|
|
||||||
squares += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return squares;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[aoc(day3, part2, Brute)]
|
#[aoc(day3, part2, Brute)]
|
||||||
|
|||||||
Reference in new issue
Block a user