From b4f9e56227819fa4950df99ba6b1ef1bf7ed4d25 Mon Sep 17 00:00:00 2001 From: Max Nuding Date: Thu, 8 Dec 2022 07:38:37 +0000 Subject: [PATCH] Parse numbers once and save to grid --- src/day08/mod.rs | 66 +++++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/src/day08/mod.rs b/src/day08/mod.rs index 3191706..85c8c55 100644 --- a/src/day08/mod.rs +++ b/src/day08/mod.rs @@ -1,72 +1,76 @@ use crate::read; pub fn run() { - let input = read("08"); - let lines = input.lines().collect::>(); + let grid: Vec> = read("08") + .lines() + .map(|l| { + l.chars() + .map(|c| c.to_digit(10).unwrap()) + .collect::>() + }) + .collect::>(); + + let width = grid.first().unwrap().len(); let mut count = 0; let mut max_score = 0; - for r in 1..lines.len() - 1 { - let row = lines[r]; - for c in 1..row.len() - 1 { - let height = row[c..=c].parse().unwrap(); - - let mut is_visible = 4; + for (row, row_vec) in grid.iter().enumerate().skip(1) { + for (col, height) in row_vec.iter().enumerate().skip(1) { + let mut sides_visible = 4; let mut score = 1; - score *= if let Some(sc_score) = (0..c) + score *= if let Some(sc_score) = (0..col) .rev() - .map(|cc| (c - cc, row[cc..=cc].parse::().unwrap())) - .find(|(_sc_score, other_height)| other_height >= &height) + .map(|cc| (col - cc, row_vec[cc])) + .find(|(_sc_score, other_height)| other_height >= height) { - is_visible -= 1; + sides_visible -= 1; sc_score.0 } else { - c + col }; - score *= if let Some(sc_score) = (c + 1..row.len()) - .map(|cc| (cc - c, row[cc..=cc].parse::().unwrap())) - .find(|(_sc_score, other_height)| other_height >= &height) + score *= if let Some(sc_score) = (col + 1..width) + .map(|cc| (cc - col, row_vec[cc])) + .find(|(_sc_score, other_height)| other_height >= height) { - is_visible -= 1; + sides_visible -= 1; sc_score.0 } else { - row.len() - c - 1 + width - col - 1 }; - score *= if let Some(sc_score) = (0..r) + score *= if let Some(sc_score) = (0..row) .rev() - .map(|rr| (r - rr, lines[rr][c..=c].parse::().unwrap())) - .find(|(_sc_score, other_height)| other_height >= &height) + .map(|rr| (row - rr, grid[rr][col])) + .find(|(_sc_score, other_height)| other_height >= height) { - is_visible -= 1; + sides_visible -= 1; sc_score.0 } else { - r + row }; - score *= if let Some(sc_score) = lines + score *= if let Some(sc_score) = grid .iter() .enumerate() - .skip(r + 1) - .map(|(rr, l)| (rr - r, l[c..=c].parse::().unwrap())) - .find(|(_sc_score, other_height)| other_height >= &height) + .skip(row + 1) + .map(|(rr, l)| (rr - row, l[col])) + .find(|(_sc_score, other_height)| other_height >= height) { - is_visible -= 1; + sides_visible -= 1; sc_score.0 } else { - lines.len() - r - 1 + grid.len() - row - 1 }; max_score = max_score.max(score); - if is_visible > 0 { + if sides_visible > 0 { count += 1; } } } - count += 2 * lines.len() + 2 * (lines[0].len() - 2); #[cfg(feature = "part1")] {