Day 8, puzzle 1
This commit is contained in:
parent
1156bc2e75
commit
03a8692162
|
@ -0,0 +1,10 @@
|
|||
use aoc22::{
|
||||
day8::{self, find_visible},
|
||||
util,
|
||||
};
|
||||
|
||||
pub fn main() {
|
||||
let grid = day8::parse_grid(&util::parse_input());
|
||||
|
||||
println!("There are {} visible trees", find_visible(&grid).len());
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
use std::collections::HashSet;
|
||||
|
||||
pub type Grid = Vec<Vec<u32>>;
|
||||
|
||||
pub fn parse_grid(input: &String) -> Grid {
|
||||
let mut result = Vec::new();
|
||||
|
||||
for line in input.lines() {
|
||||
result.push(line.chars().map(|c| c.to_digit(10).unwrap()).collect());
|
||||
}
|
||||
|
||||
let row_lens: Vec<usize> = result.iter().map(Vec::len).collect();
|
||||
assert_eq!(row_lens.iter().max(), row_lens.iter().min());
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub type Coordinate = (usize, usize);
|
||||
|
||||
pub fn find_visible(grid: &Grid) -> HashSet<Coordinate> {
|
||||
let mut result = HashSet::new();
|
||||
|
||||
let rows = grid.len();
|
||||
assert!(rows > 0);
|
||||
let cols = grid.get(0).unwrap().len();
|
||||
assert!(cols > 0);
|
||||
|
||||
for row in 0..rows {
|
||||
let mut left_indices = (0..cols).map(|c| (row, c));
|
||||
let mut right_indices = left_indices.clone().rev();
|
||||
result.extend(check_indices(&grid, &mut left_indices));
|
||||
result.extend(check_indices(&grid, &mut right_indices));
|
||||
}
|
||||
for col in 0..cols {
|
||||
let mut top_indices = (0..rows).map(|r| (r, col));
|
||||
let mut bottom_indices = top_indices.clone().rev();
|
||||
result.extend(check_indices(&grid, &mut top_indices));
|
||||
result.extend(check_indices(&grid, &mut bottom_indices));
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn check_indices(grid: &Grid, coords: &mut dyn Iterator<Item = Coordinate>) -> Vec<Coordinate> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
let mut max_height: i64 = -1;
|
||||
for (row, col) in coords {
|
||||
let height = *grid.get(row).unwrap().get(col).unwrap() as i64;
|
||||
if height > max_height {
|
||||
result.push((row, col));
|
||||
max_height = height;
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
|
@ -5,4 +5,5 @@ pub mod day4;
|
|||
pub mod day5;
|
||||
pub mod day6;
|
||||
pub mod day7;
|
||||
pub mod day8;
|
||||
pub mod util;
|
||||
|
|
Loading…
Reference in New Issue