2021 day5/rust: dedup using Vec matrix instead of HashMap

This commit is contained in:
Xiretza 2021-12-05 11:44:09 +01:00
parent 4ee0046b97
commit 83b9b79a28

View file

@ -1,6 +1,5 @@
#![warn(clippy::pedantic)] #![warn(clippy::pedantic)]
use std::{ use std::{
collections::HashMap,
convert::Infallible, convert::Infallible,
io::{stdin, BufRead}, io::{stdin, BufRead},
str::FromStr, str::FromStr,
@ -58,14 +57,27 @@ impl FromStr for Line {
} }
fn count_overlaps<'a>(it: impl IntoIterator<Item = &'a Line>) -> usize { fn count_overlaps<'a>(it: impl IntoIterator<Item = &'a Line>) -> usize {
let counts: HashMap<(usize, usize), usize> = let points: Vec<(usize, usize)> = it
it.into_iter() .into_iter()
.flat_map(Line::expand) .flat_map(Line::expand)
.fold(HashMap::new(), |mut map, point| { .map(Into::into)
*map.entry(point.into()).or_default() += 1; .collect();
map
}); let (max_x, max_y) = points.iter().fold((0, 0), |(acc_x, acc_y), &(x, y)| {
counts.into_iter().filter(|&(_k, v)| v >= 2).count() (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() { fn main() {