adventofcode2022/day08/part2.rs

59 lines
2.1 KiB
Rust
Raw Normal View History

2022-12-08 16:21:38 +01:00
// Copyright 2022 Christian Ulrich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// usage: ./part2 < input
pub mod common;
use common::Forest;
fn main() -> Result<(), &'static str> {
let forest = Forest::from_stdin()?;
let (x_len, y_len) = forest.dimensions();
let mut result = 0;
for y in 0..y_len {
for x in 0..x_len {
let line = forest.line(y).unwrap().collect::<Vec<_>>();
let column = forest.column(x).unwrap().collect::<Vec<_>>();
let west = Box::new(line[..x].iter().rev().cloned());
let east = Box::new(line[x + 1..].iter().cloned());
let north = Box::new(column[..y].iter().rev().cloned());
let south = Box::new(column[y + 1..].iter().cloned());
let views: [Box<dyn Iterator<Item = _>>; 4] = [west, east, north, south];
let tree = forest.tree(x, y).unwrap();
let mut scenic_score = 1;
for view in views {
let mut viewing_distance = 0;
for t in view {
match t {
_ if { t >= &tree } => {
viewing_distance += 1;
break;
}
_ if { t < &tree } => viewing_distance += 1,
_ => break,
}
}
scenic_score *= viewing_distance;
}
result = usize::max(result, scenic_score);
}
}
println!("{result}");
Ok(())
}