summaryrefslogtreecommitdiffstats
path: root/2021/day9/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to '2021/day9/src/main.rs')
-rw-r--r--2021/day9/src/main.rs67
1 files changed, 67 insertions, 0 deletions
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 @@
1use std::env;
2use std::fs::File;
3use std::io::{BufRead, BufReader};
4
5fn main() {
6 let reader = open_file();
7
8 let mut points: Vec<Vec<u32>> = Vec::new();
9
10 for line in reader.lines() {
11 points.push(
12 line.unwrap()
13 .trim()
14 .chars()
15 .map(|x| x.to_digit(10).unwrap())
16 .collect(),
17 );
18 }
19
20 let nine = vec![9];
21
22 let mut risk_level: u32 = 0;
23
24 for (idx, height) in points.iter().enumerate() {
25 for (ndx, num) in height.iter().enumerate() {
26 let up = points
27 .get(((idx as isize) - 1) as usize)
28 .unwrap_or_else(|| &nine)
29 .get(ndx)
30 .unwrap_or_else(|| &9);
31
32 let down = match points.get(idx + 1) {
33 Some(line) => match line.get(ndx) {
34 Some(number) => number,
35 None => &9,
36 },
37 None => &9,
38 };
39 let left = match height.get((ndx as isize - 1) as usize) {
40 Some(number) => number,
41 None => &9,
42 };
43 let right = match height.get(ndx + 1) {
44 Some(number) => number,
45 None => &9,
46 };
47 if num < up && num < down && num < right && num < left {
48 risk_level += 1 + *num;
49 }
50 }
51 }
52 println!("{}", risk_level);
53}
54
55fn open_file() -> BufReader<File> {
56 let args: Vec<String> = env::args().collect();
57
58 if args.len() != 2 {
59 eprintln!("Usage: {} <filename>", args[0]);
60 std::process::exit(1);
61 }
62
63 let filename = &args[1];
64
65 let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename));
66 BufReader::new(file)
67}