2022 day8/rust: add solution

This commit is contained in:
Xiretza 2022-12-08 07:25:38 +01:00
parent 06aa5677e1
commit 66fa9d1c35
4 changed files with 91 additions and 0 deletions

View file

@ -0,0 +1,9 @@
[package]
name = "rust_2022_08"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aoc = { path = "../../../common/rust" }

View file

@ -0,0 +1,74 @@
#![warn(clippy::pedantic)]
use std::io::{stdin, Read};
use aoc::*;
#[derive(Debug, Clone, Copy)]
struct Tree {
height: u32,
visible: bool,
score: usize,
}
fn make_visible<'a>(trees: impl IntoIterator<Item = &'a mut Tree>) {
let mut seen: Vec<Tree> = Vec::new();
let mut highest: Option<Tree> = None;
for tree in trees {
let update = match highest {
None => true,
Some(highest) => tree.height > highest.height,
};
if update {
tree.visible = true;
highest = Some(*tree);
}
let mut score = 0;
for t in seen.iter().rev() {
score += 1;
if t.height >= tree.height {
break;
}
}
tree.score *= score;
seen.push(*tree);
}
}
fn main() {
let mut data = String::new();
stdin().read_to_string(&mut data).unwrap();
let mut grid: Vec<Vec<Tree>> = data
.lines()
.map(|line| {
line.chars()
.map(|c| Tree {
height: c.to_digit(10).unwrap(),
visible: false,
score: 1,
})
.collect()
})
.collect();
for line in &mut grid {
make_visible(line.iter_mut());
make_visible(line.iter_mut().rev());
}
let width = grid[0].len();
for i in 0..width {
make_visible(grid.iter_mut().map(|l| &mut l[i]));
make_visible(grid.iter_mut().map(|l| &mut l[i]).rev());
}
println!("{:?}", grid.iter().flatten().filter(|&t| t.visible).count());
println!(
"{:?}",
grid.iter().flatten().map(|t| t.score).max().unwrap()
);
}

7
Cargo.lock generated
View file

@ -517,6 +517,13 @@ dependencies = [
"aoc", "aoc",
] ]
[[package]]
name = "rust_2022_08"
version = "0.1.0"
dependencies = [
"aoc",
]
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.11" version = "1.0.11"

View file

@ -17,4 +17,5 @@ members = [
"2022/day5/rust", "2022/day5/rust",
"2022/day6/rust", "2022/day6/rust",
"2022/day7/rust", "2022/day7/rust",
"2022/day8/rust",
] ]