1
0
Fork 0

day(18): separate by rows

Allows to paralelize by rows.

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2023-12-18 22:09:15 +01:00
parent 9a5d814792
commit 2e889073cd
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -1,7 +1,6 @@
use std::{ use std::{collections::BTreeMap, str::FromStr};
collections::BTreeMap,
str::FromStr, use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
};
use aoc_2023::*; use aoc_2023::*;
@ -64,32 +63,44 @@ fn opposite(u: (isize, isize)) -> (isize, isize) {
} }
fn solve(plan: &[Step]) -> usize { fn solve(plan: &[Step]) -> usize {
let mut hole: BTreeMap<Vector2D<isize>, u8> = BTreeMap::new(); let mut hole: BTreeMap<isize, BTreeMap<isize, u8>> = BTreeMap::new();
let mut position = Vector2D::new(0, 0); let mut position = Vector2D::new(0, 0);
for s in plan.iter() { for s in plan.iter() {
let direction = s.direction(); let direction = s.direction();
for _ in 0..s.count { 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; 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; hole.par_iter().map(|(_, row)| row.len()).sum::<usize>()
+ hole
.par_iter()
.map(|(_y, row)| {
let mut in_between = 0; let mut in_between = 0;
let mut x_prev = 0; let mut x_prev = 0;
for (v, directions) in hole.iter() {
if in_between != 0 && x_prev < v.x() { let mut counter = 0;
// debug!("{} {}", v.x(), x_prev); for (x, directions) in row.iter() {
counter += (v.x() - x_prev) as usize - 1; if in_between != 0 {
let cells_between = (x - x_prev) as usize - 1;
counter += cells_between;
} }
in_between ^= directions & 3; in_between ^= directions & 3;
x_prev = v.x(); x_prev = *x;
} }
counter + hole.len() counter
})
.sum::<usize>()
} }
struct Day18 { struct Day18 {