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