diff --git a/src/bin/day18.rs b/src/bin/day18.rs index 28f49a3..d12160f 100644 --- a/src/bin/day18.rs +++ b/src/bin/day18.rs @@ -1,7 +1,6 @@ -use std::{ - collections::BTreeMap, - str::FromStr, -}; +use std::{collections::BTreeMap, str::FromStr}; + +use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use aoc_2023::*; @@ -64,32 +63,44 @@ fn opposite(u: (isize, isize)) -> (isize, isize) { } fn solve(plan: &[Step]) -> usize { - let mut hole: BTreeMap, u8> = BTreeMap::new(); + let mut hole: BTreeMap> = BTreeMap::new(); let mut position = Vector2D::new(0, 0); for s in plan.iter() { let direction = s.direction(); for _ in 0..s.count { - *hole.entry(position).or_insert(0) |= dir_to_u8(s._direction); + *(*hole.entry(position.y()).or_default()) + .entry(position.x()) + .or_default() |= dir_to_u8(s._direction); position = position + direction; - *hole.entry(position).or_insert(0) |= dir_to_u8(opposite(s._direction)); + *(*hole.entry(position.y()).or_default()) + .entry(position.x()) + .or_default() |= dir_to_u8(opposite(s._direction)); } } - let mut counter = 0; - let mut in_between = 0; - let mut x_prev = 0; - for (v, directions) in hole.iter() { - if in_between != 0 && x_prev < v.x() { - // debug!("{} {}", v.x(), x_prev); - counter += (v.x() - x_prev) as usize - 1; - } - in_between ^= directions & 3; - x_prev = v.x(); - } + hole.par_iter().map(|(_, row)| row.len()).sum::() + + hole + .par_iter() + .map(|(_y, row)| { + let mut in_between = 0; + let mut x_prev = 0; - counter + hole.len() + let mut counter = 0; + for (x, directions) in row.iter() { + if in_between != 0 { + let cells_between = (x - x_prev) as usize - 1; + + counter += cells_between; + } + in_between ^= directions & 3; + x_prev = *x; + } + + counter + }) + .sum::() } struct Day18 {