[rs] Solve 2022_08 part 1

This commit is contained in:
Joscha 2022-12-08 08:47:48 +01:00
parent 378b5e38ae
commit 6b4aeebf03
7 changed files with 176 additions and 0 deletions

View file

@ -47,6 +47,7 @@ days! {
Y2022D05: "2022_05",
Y2022D06: "2022_06",
Y2022D07: "2022_07",
Y2022D08: "2022_08",
}
#[derive(Parser)]
@ -77,6 +78,7 @@ fn main() -> io::Result<()> {
Day::Y2022D05 => y2022::d05::solve(input),
Day::Y2022D06 => y2022::d06::solve(input),
Day::Y2022D07 => y2022::d07::solve(input),
Day::Y2022D08 => y2022::d08::solve(input),
}
eprintln!()
}

View file

@ -5,3 +5,4 @@ pub mod d04;
pub mod d05;
pub mod d06;
pub mod d07;
pub mod d08;

65
rs/src/y2022/d08.rs Normal file
View file

@ -0,0 +1,65 @@
struct Tree {
height: u8,
visible: bool,
}
struct Grid {
width: usize,
height: usize,
trees: Vec<Tree>,
}
impl Grid {
fn parse(str: &str) -> Self {
let width = str.lines().next().unwrap().len();
let height = str.lines().count();
let trees = str
.lines()
.flat_map(|l| l.chars())
.map(|c| Tree {
height: (c as u32 - '0' as u32) as u8,
visible: false,
})
.collect();
Self {
width,
height,
trees,
}
}
fn at_mut(&mut self, x: usize, y: usize) -> Option<&mut Tree> {
if x >= self.width || y >= self.height {
None
} else {
Some(&mut self.trees[y * self.width + x])
}
}
fn scan_visibility(&mut self, xy: impl Iterator<Item = (usize, usize)>) {
let mut max_height = 0;
for (x, y) in xy {
let tree = self.at_mut(x, y).unwrap();
if tree.height >= max_height {
tree.visible = true;
max_height = tree.height + 1;
}
}
}
}
pub fn solve(input: String) {
let mut trees = Grid::parse(&input);
for y in 0..trees.height {
trees.scan_visibility((0..trees.width).map(|x| (x, y)));
trees.scan_visibility((0..trees.width).map(|x| (x, y)).rev());
}
for x in 0..trees.width {
trees.scan_visibility((0..trees.height).map(|y| (x, y)));
trees.scan_visibility((0..trees.height).map(|y| (x, y)).rev());
}
let part1 = trees.trees.iter().filter(|t| t.visible).count();
println!("Part 1: {part1}");
}