1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let reader = open_file();
let mut points: Vec<Vec<u32>> = 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<File> {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: {} <filename>", 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)
}
|