From 9a64352fc322d132ea9e93bcd0525b7b9de08141 Mon Sep 17 00:00:00 2001 From: jazzpi Date: Wed, 14 Dec 2022 16:25:10 +0100 Subject: [PATCH] Day 8, puzzle 2 --- src/bin/d8p2.rs | 22 ++++++++++++++++++++++ src/day8.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/bin/d8p2.rs diff --git a/src/bin/d8p2.rs b/src/bin/d8p2.rs new file mode 100644 index 0000000..e2018e6 --- /dev/null +++ b/src/bin/d8p2.rs @@ -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); +} diff --git a/src/day8.rs b/src/day8.rs index b5b11dd..2aedce4 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -55,3 +55,38 @@ fn check_indices(grid: &Grid, coords: &mut dyn Iterator) -> 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> = + 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, +) -> 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 +}