Day 8, puzzle 2

This commit is contained in:
jazzpi 2022-12-14 16:25:10 +01:00
parent 03a8692162
commit 9a64352fc3
2 changed files with 57 additions and 0 deletions

22
src/bin/d8p2.rs Normal file
View File

@ -0,0 +1,22 @@
use aoc22::{
day8::{self, calc_scenic_score},
util,
};
pub fn main() {
let grid = day8::parse_grid(&util::parse_input());
let rows = grid.len();
assert!(rows > 0);
let cols = grid.get(0).unwrap().len();
assert!(cols > 0);
let max_score = (0..rows)
.map(move |r| (0..cols).map(move |c| (r, c)))
.flatten()
.map(|c| calc_scenic_score(&grid, c))
.max()
.unwrap();
println!("Max scenic score is {}", max_score);
}

View File

@ -55,3 +55,38 @@ fn check_indices(grid: &Grid, coords: &mut dyn Iterator<Item = Coordinate>) -> V
result
}
pub fn calc_scenic_score(grid: &Grid, (row, col): Coordinate) -> usize {
let rows = grid.len();
assert!(rows > 0);
let cols = grid.get(0).unwrap().len();
assert!(cols > 0);
let height = *grid.get(row).unwrap().get(col).unwrap();
let mut left = (0..col).map(|c| (row, c)).rev();
let mut right = (col + 1..cols).map(|c| (row, c));
let mut up = (0..row).map(|r| (r, col)).rev();
let mut down = (row + 1..rows).map(|r| (r, col));
let mut directions: Vec<&mut dyn Iterator<Item = Coordinate>> =
vec![&mut left, &mut right, &mut up, &mut down];
directions
.iter_mut()
.map(|d| calc_viewing_distance(grid, height, *d))
.product()
}
fn calc_viewing_distance(
grid: &Grid,
start_height: u32,
coords: &mut dyn Iterator<Item = Coordinate>,
) -> usize {
let mut result = 0;
for (row, col) in coords {
result += 1;
let height = *grid.get(row).unwrap().get(col).unwrap();
if height >= start_height {
break;
}
}
result
}