Parse numbers once and save to grid

This commit is contained in:
Max Nuding 2022-12-08 07:38:37 +00:00
parent 17733c951f
commit b4f9e56227

View File

@ -1,72 +1,76 @@
use crate::read; use crate::read;
pub fn run() { pub fn run() {
let input = read("08"); let grid: Vec<Vec<u32>> = read("08")
let lines = input.lines().collect::<Vec<_>>(); .lines()
.map(|l| {
l.chars()
.map(|c| c.to_digit(10).unwrap())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let width = grid.first().unwrap().len();
let mut count = 0; let mut count = 0;
let mut max_score = 0; let mut max_score = 0;
for r in 1..lines.len() - 1 { for (row, row_vec) in grid.iter().enumerate().skip(1) {
let row = lines[r]; for (col, height) in row_vec.iter().enumerate().skip(1) {
for c in 1..row.len() - 1 { let mut sides_visible = 4;
let height = row[c..=c].parse().unwrap();
let mut is_visible = 4;
let mut score = 1; let mut score = 1;
score *= if let Some(sc_score) = (0..c) score *= if let Some(sc_score) = (0..col)
.rev() .rev()
.map(|cc| (c - cc, row[cc..=cc].parse::<usize>().unwrap())) .map(|cc| (col - cc, row_vec[cc]))
.find(|(_sc_score, other_height)| other_height >= &height) .find(|(_sc_score, other_height)| other_height >= height)
{ {
is_visible -= 1; sides_visible -= 1;
sc_score.0 sc_score.0
} else { } else {
c col
}; };
score *= if let Some(sc_score) = (c + 1..row.len()) score *= if let Some(sc_score) = (col + 1..width)
.map(|cc| (cc - c, row[cc..=cc].parse::<usize>().unwrap())) .map(|cc| (cc - col, row_vec[cc]))
.find(|(_sc_score, other_height)| other_height >= &height) .find(|(_sc_score, other_height)| other_height >= height)
{ {
is_visible -= 1; sides_visible -= 1;
sc_score.0 sc_score.0
} else { } 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() .rev()
.map(|rr| (r - rr, lines[rr][c..=c].parse::<usize>().unwrap())) .map(|rr| (row - rr, grid[rr][col]))
.find(|(_sc_score, other_height)| other_height >= &height) .find(|(_sc_score, other_height)| other_height >= height)
{ {
is_visible -= 1; sides_visible -= 1;
sc_score.0 sc_score.0
} else { } else {
r row
}; };
score *= if let Some(sc_score) = lines score *= if let Some(sc_score) = grid
.iter() .iter()
.enumerate() .enumerate()
.skip(r + 1) .skip(row + 1)
.map(|(rr, l)| (rr - r, l[c..=c].parse::<usize>().unwrap())) .map(|(rr, l)| (rr - row, l[col]))
.find(|(_sc_score, other_height)| other_height >= &height) .find(|(_sc_score, other_height)| other_height >= height)
{ {
is_visible -= 1; sides_visible -= 1;
sc_score.0 sc_score.0
} else { } else {
lines.len() - r - 1 grid.len() - row - 1
}; };
max_score = max_score.max(score); max_score = max_score.max(score);
if is_visible > 0 { if sides_visible > 0 {
count += 1; count += 1;
} }
} }
} }
count += 2 * lines.len() + 2 * (lines[0].len() - 2);
#[cfg(feature = "part1")] #[cfg(feature = "part1")]
{ {