diff --git a/day08/Cargo.lock b/day08/Cargo.lock new file mode 100644 index 0000000..1d4626c --- /dev/null +++ b/day08/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "day08" +version = "0.1.0" diff --git a/day08/Cargo.toml b/day08/Cargo.toml new file mode 100644 index 0000000..7156aba --- /dev/null +++ b/day08/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day08" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/day08/src/main.rs b/day08/src/main.rs new file mode 100644 index 0000000..5d1b357 --- /dev/null +++ b/day08/src/main.rs @@ -0,0 +1,63 @@ +use std::error; +use std::fs::File; +use std::io::BufRead; +use std::io::BufReader; + +fn main() -> Result<(), Box> { + let f = File::open("input.txt")?; + let reader = BufReader::new(f); + + let mut map = vec![]; + let mut width = 0; + for line in reader.lines() { + let line = line?; + + width = line.len(); + map.extend(line.chars().map(|c| c.to_digit(10)).flatten().map(|d| d as usize)); + } + + let width = width; + let height = map.len() / width; + + let mut visible_count = 0; + for i in 0..map.len() { + let line = i / height; + let column = i % width + 1; // we need + 1 here, because there is no modulo 0 + + // println!("line: {}, column: {}, self: {}", line, column, map[i]); + let left = map[(line * width)..i].iter().max(); + let right = map[i..((line + 1) * width)].iter() + .enumerate() + .filter_map(|(j, x)| if (j + i) / height == line && j > 0 { Some(x) } else { None }) + .max(); + // let right = map[(i + 1)..((line + 1) * width)].iter().max(); + let up = map[0..i].iter() + .enumerate() + //.inspect(|(j, x)| println!("{j} {x}")) + .filter_map(|(j, x)| if (j + 1) % width == column { Some(x) } else { None }) + .max(); + let down = map[i..].iter() + .enumerate() + .filter_map(|(j, x)| if (i + j + 1) % width == column && j > 0 { Some(x) } else { None }) + .max(); + // println!("left: {:?}, right: {:?}, up: {:?}, down: {:?}", &left, &right, &up, &down); + + for direction_max in vec![left, right, up, down] { + match direction_max { + Some(x) if x < &map[i] => { + visible_count += 1; + break; + }, + None => { + visible_count += 1; + break; + }, + _ => () + } + } + // println!("visible: {visible_count}"); + } + + println!("Found {visible_count} visible trees."); + Ok(()) +}