From 4f913109c74daa869d91798848c26b382a14e17c Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Mon, 13 Dec 2021 18:58:37 +0300 Subject: 2021, day9: part1 --- 2021/day9/src/main.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 2021/day9/src/main.rs (limited to '2021/day9/src') diff --git a/2021/day9/src/main.rs b/2021/day9/src/main.rs new file mode 100644 index 0000000..75bf1e9 --- /dev/null +++ b/2021/day9/src/main.rs @@ -0,0 +1,67 @@ +use std::env; +use std::fs::File; +use std::io::{BufRead, BufReader}; + +fn main() { + let reader = open_file(); + + let mut points: Vec> = Vec::new(); + + for line in reader.lines() { + points.push( + line.unwrap() + .trim() + .chars() + .map(|x| x.to_digit(10).unwrap()) + .collect(), + ); + } + + let nine = vec![9]; + + let mut risk_level: u32 = 0; + + for (idx, height) in points.iter().enumerate() { + for (ndx, num) in height.iter().enumerate() { + let up = points + .get(((idx as isize) - 1) as usize) + .unwrap_or_else(|| &nine) + .get(ndx) + .unwrap_or_else(|| &9); + + let down = match points.get(idx + 1) { + Some(line) => match line.get(ndx) { + Some(number) => number, + None => &9, + }, + None => &9, + }; + let left = match height.get((ndx as isize - 1) as usize) { + Some(number) => number, + None => &9, + }; + let right = match height.get(ndx + 1) { + Some(number) => number, + None => &9, + }; + if num < up && num < down && num < right && num < left { + risk_level += 1 + *num; + } + } + } + println!("{}", risk_level); +} + +fn open_file() -> BufReader { + let args: Vec = env::args().collect(); + + if args.len() != 2 { + eprintln!("Usage: {} ", args[0]); + std::process::exit(1); + } + + let filename = &args[1]; + + let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename)); + BufReader::new(file) +} -- cgit v1.2.3-70-g09d2