From aeb6d67196f501f3c401e43bfa3d95fed1503e51 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Tue, 10 Dec 2024 21:03:10 +0100 Subject: [PATCH] More efficient matrix construction during data parsing --- src/day06.rs | 21 ++++++++++----------- src/day08.rs | 20 +++++++------------- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/src/day06.rs b/src/day06.rs index f027095..2f771be 100644 --- a/src/day06.rs +++ b/src/day06.rs @@ -7,26 +7,25 @@ type Pos = Point2; type Dir = Vector2; pub fn read_map(reader: &mut dyn BufRead) -> (Map, Pos) { - let mut map = DMatrix::default(); let mut guard_position = Pos::default(); + let mut data: Vec = Vec::new(); + let mut nb_rows = 0; + for (i, l) in reader.lines().enumerate() { - if map.nrows() < i + 1 { - map = map.insert_row(i, false); - } + nb_rows += 1; for (j, c) in l.unwrap().chars().enumerate() { - if map.ncols() < j + 1 { - map = map.insert_column(j, false); - } - if c == '#' { - map[(i, j)] = true; - } else if c == '^' { + data.push(c == '#'); + if c == '^' { guard_position = Pos::new(i as i32, j as i32); } } } - (map, guard_position) + ( + Map::from_row_slice(nb_rows, data.len() / nb_rows, &data), + guard_position, + ) } const ROT_MAT: Matrix2 = Matrix2::new(0, 1, -1, 0); diff --git a/src/day08.rs b/src/day08.rs index 55d2816..00162ce 100644 --- a/src/day08.rs +++ b/src/day08.rs @@ -9,23 +9,17 @@ type Antinodes = DMatrix; const EMPTY: char = ' '; pub fn read(reader: &mut dyn BufRead) -> Antennae { - let mut antennae = Antennae::default(); + let mut data: Vec = Vec::new(); + let mut nb_rows = 0; - for (i, l) in reader.lines().enumerate() { - if antennae.nrows() < i + 1 { - antennae = antennae.insert_row(i, EMPTY); - } - for (j, c) in l.unwrap().chars().enumerate() { - if antennae.ncols() < j + 1 { - antennae = antennae.insert_column(j, EMPTY); - } - if c != '.' { - antennae[(i, j)] = c; - } + for l in reader.lines() { + nb_rows += 1; + for c in l.unwrap().chars() { + data.push(if c == '.' { EMPTY } else { c }); } } - antennae + Antennae::from_row_slice(nb_rows, data.len() / nb_rows, &data) } pub enum AntinodeMode { TwoPerPair, -- 2.45.2