2026/day3: add 'optimized' pairwise implementation, but it is way slower
This commit is contained in:
1 file changed
+34
-7
+34
-7
@@ -1,6 +1,7 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use grid::{Coord2d, Grid};
|
||||
use std::str::FromStr;
|
||||
use grid::{AsCoord2d, Coord2d, Grid};
|
||||
use itertools::Itertools;
|
||||
use std::{collections::BTreeSet, str::FromStr};
|
||||
|
||||
#[aoc_generator(day3)]
|
||||
fn parse(input: &str) -> Grid<u8> {
|
||||
@@ -58,10 +59,32 @@ fn rotated_offsets(initial: Coord2d) -> [Coord2d; 3] {
|
||||
]
|
||||
}
|
||||
|
||||
#[aoc(day3, part2)]
|
||||
fn part2(input: &Grid<u8>) -> u64 {
|
||||
let biggest_square = std::cmp::min(input.width(), input.height());
|
||||
// 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.
|
||||
#[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]]
|
||||
.iter()
|
||||
.permutations(2)
|
||||
{
|
||||
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)]
|
||||
fn part2_brute(input: &Grid<u8>) -> u64 {
|
||||
let biggest_square = std::cmp::min(input.width(), input.height());
|
||||
input
|
||||
.find_all(&b'#')
|
||||
.map(|tree| {
|
||||
@@ -163,7 +186,11 @@ mod tests {
|
||||
#######",
|
||||
196
|
||||
)]
|
||||
fn part2_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part2(&parse(input)), expected);
|
||||
fn part2_example(
|
||||
#[case] input: &str,
|
||||
#[case] expected: u64,
|
||||
#[values(part2_brute, part2_pairwise)] version: fn(&Grid<u8>) -> u64,
|
||||
) {
|
||||
assert_eq!(version(&parse(input)), expected);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user