From c63c23c252d4c867142b08a47b187845b1d073e0 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sun, 5 Dec 2021 11:44:09 +0100 Subject: [PATCH] 2021 day5/rust: dedup using Vec matrix instead of HashMap --- 2021/day5/day5_rs/src/main.rs | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/2021/day5/day5_rs/src/main.rs b/2021/day5/day5_rs/src/main.rs index 5783430..d8a07ea 100644 --- a/2021/day5/day5_rs/src/main.rs +++ b/2021/day5/day5_rs/src/main.rs @@ -1,6 +1,5 @@ #![warn(clippy::pedantic)] use std::{ - collections::HashMap, convert::Infallible, io::{stdin, BufRead}, str::FromStr, @@ -58,14 +57,27 @@ impl FromStr for Line { } fn count_overlaps<'a>(it: impl IntoIterator) -> usize { - let counts: HashMap<(usize, usize), usize> = - it.into_iter() - .flat_map(Line::expand) - .fold(HashMap::new(), |mut map, point| { - *map.entry(point.into()).or_default() += 1; - map - }); - counts.into_iter().filter(|&(_k, v)| v >= 2).count() + let points: Vec<(usize, usize)> = it + .into_iter() + .flat_map(Line::expand) + .map(Into::into) + .collect(); + + let (max_x, max_y) = points.iter().fold((0, 0), |(acc_x, acc_y), &(x, y)| { + (usize::max(acc_x, x), usize::max(acc_y, y)) + }); + + let mut field = vec![vec![0_usize; max_y + 1]; max_x + 1]; + + let mut hits = 0; + for (x, y) in points { + let point = &mut field[x][y]; + if *point == 1 { + hits += 1; + } + *point += 1; + } + hits } fn main() {