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) }