From 66fa9d1c35caadb55bf4f77f25f87c2dd8841c73 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Thu, 8 Dec 2022 07:25:38 +0100 Subject: [PATCH] 2022 day8/rust: add solution --- 2022/day8/rust/Cargo.toml | 9 +++++ 2022/day8/rust/src/main.rs | 74 ++++++++++++++++++++++++++++++++++++++ Cargo.lock | 7 ++++ Cargo.toml | 1 + 4 files changed, 91 insertions(+) create mode 100644 2022/day8/rust/Cargo.toml create mode 100644 2022/day8/rust/src/main.rs diff --git a/2022/day8/rust/Cargo.toml b/2022/day8/rust/Cargo.toml new file mode 100644 index 0000000..d0c42b2 --- /dev/null +++ b/2022/day8/rust/Cargo.toml @@ -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" } diff --git a/2022/day8/rust/src/main.rs b/2022/day8/rust/src/main.rs new file mode 100644 index 0000000..8f62c70 --- /dev/null +++ b/2022/day8/rust/src/main.rs @@ -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) { + let mut seen: Vec = Vec::new(); + let mut highest: Option = 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> = 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() + ); +} diff --git a/Cargo.lock b/Cargo.lock index df24bd5..2712dc6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -517,6 +517,13 @@ dependencies = [ "aoc", ] +[[package]] +name = "rust_2022_08" +version = "0.1.0" +dependencies = [ + "aoc", +] + [[package]] name = "ryu" version = "1.0.11" diff --git a/Cargo.toml b/Cargo.toml index 2581d97..9f1ad8a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,4 +17,5 @@ members = [ "2022/day5/rust", "2022/day6/rust", "2022/day7/rust", + "2022/day8/rust", ]