use aoc_runner_derive::{aoc, aoc_generator}; use grid::{Coord2d, Grid}; use std::str::FromStr; #[aoc_generator(day3)] fn parse(input: &str) -> Grid { Grid::from_str(input).unwrap() } #[aoc(day3, part1)] fn part1(input: &Grid) -> u64 { let mut squares: u64 = 0; let biggest_square = std::cmp::min(input.width(), input.height()); // For each tree in the input grid, look at possible squares right and down from it for tree in input.find_all(&b'#') { for size in 1..(biggest_square - tree.x as usize) { if input .get(&(tree + &Coord2d { x: size as i64, y: 0 })) .is_some_and(|c| *c == b'#') && input .get(&(tree + &Coord2d { y: size as i64, x: 0 })) .is_some_and(|c| *c == b'#') && input .get( &(tree + &Coord2d { x: size as i64, y: size as i64, }), ) .is_some_and(|c| *c == b'#') { squares += 1 } } } squares } // Given the offset of the first (of 3) other square corners, return the full set fn rotated_offsets(initial: Coord2d) -> [Coord2d; 3] { [ initial, Coord2d { x: initial.x - initial.y, y: initial.x + initial.y, }, Coord2d { x: -initial.y, y: initial.x, }, ] } #[aoc(day3, part2)] fn part2(input: &Grid) -> u64 { let mut squares: u64 = 0; let biggest_square = std::cmp::min(input.width(), input.height()); // println!("{input}"); for tree in input.find_all(&b'#') { // println!("START {tree}"); for size in 1..=biggest_square { // println!(" len: {size}"); for x_ofs in 1..=size as i64 { let y_ofs = size as i64 - x_ofs; // print!(" + ({x_ofs}, {y_ofs}) - "); if rotated_offsets(Coord2d { x: x_ofs, y: y_ofs }) .iter() // .inspect(|c| print!("{c}")) .all(|ofs| input.get(&(tree + ofs)) == Some(&b'#')) { // print!(" - hit"); squares += 1; } // println!() } } } squares } #[cfg(test)] mod tests { use super::*; use rstest::rstest; const EXAMPLE1: &str = "#.### .##.# ##.## .#.#. .##.#"; const EXAMPLE2: &str = ".##.. .##.# ..... #.##. ..##."; const EXAMPLE3: &str = "##### ##### ##### ##### #####"; #[rstest] #[case(EXAMPLE1, 1u64)] #[case(EXAMPLE2, 2u64)] #[case(EXAMPLE3, 30u64)] fn part1_example(#[case] input: &str, #[case] expected: u64) { assert_eq!(part1(&parse(input)), expected); } #[rstest] #[case( ".#... ....# ..... #.... ...#.", 1 )] #[case( "..#.. ..... #...# ..... ..#..", 1 )] #[case( "....#.. ....... #...... ....... ......# ....... ..#....", 1 )] #[case( "####### ####### ####### ####### ####### ####### #######", 196 )] fn part2_example(#[case] input: &str, #[case] expected: u64) { assert_eq!(part2(&parse(input)), expected); } }