From ac2b6a486768c2579d11230c63f7cda4b96adeb8 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Sun, 8 Dec 2024 17:07:06 +0100 Subject: [PATCH] Simplify day 08. --- src/day08.rs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/day08.rs b/src/day08.rs index 62f545b..1aec6bd 100644 --- a/src/day08.rs +++ b/src/day08.rs @@ -35,6 +35,10 @@ pub enum AntinodeMode { Unlimited, } +fn inside(p: (i32, i32), limits: (usize, usize)) -> bool { + p.0 >= 0 && p.0 < limits.0 as i32 && p.1 >= 0 && p.1 < limits.1 as i32 +} + fn antinode_positions( pos: Vec<&(usize, usize)>, mode: &AntinodeMode, @@ -47,32 +51,32 @@ fn antinode_positions( pos[1].1 as i32, ); let (dx, dy) = (p1x - p2x, p1y - p2y); + let mut antinodes = Vec::new(); match mode { - AntinodeMode::TwoPerPair => vec![(p1x + dx, p1y + dy), (p2x - dx, p2y - dy)], + AntinodeMode::TwoPerPair => { + let (a1, a2) = ((p1x + dx, p1y + dy), (p2x - dx, p2y - dy)); + if inside(a1, limits) { + antinodes.push(a1); + } + if inside(a2, limits) { + antinodes.push(a2); + } + } AntinodeMode::Unlimited => { - let mut antinodes = Vec::new(); let (mut current1, mut current2) = ((p1x, p1y), (p2x, p2y)); - while current1.0 >= 0 - && current1.0 < limits.0 as i32 - && current1.1 >= 0 - && current1.1 < limits.1 as i32 - { + while inside(current1, limits) { antinodes.push(current1); current1 = (current1.0 + dx, current1.1 + dy); } - while current2.0 >= 0 - && current2.0 < limits.0 as i32 - && current2.1 >= 0 - && current2.1 < limits.1 as i32 - { + while inside(current2, limits) { antinodes.push(current2); current2 = (current2.0 - dx, current2.1 - dy); } - antinodes } } + antinodes } pub fn nb_antinodes(antennae: &Antennae, mode: AntinodeMode) -> i32 { @@ -98,10 +102,6 @@ pub fn nb_antinodes(antennae: &Antennae, mode: AntinodeMode) -> i32 { .map(|positions| antinode_positions(positions, &mode, (nr, nc))) .flatten() { - if x < 0 || x >= nc as i32 || y < 0 || y >= nr as i32 { - continue; - } - if !antinodes[(x as usize, y as usize)] { antinodes[(x as usize, y as usize)] = true; nb_antinodes += 1; -- 2.45.2