diff options
author | Yigit Sever | 2021-12-13 18:58:37 +0300 |
---|---|---|
committer | Yigit Sever | 2021-12-13 18:58:37 +0300 |
commit | 4f913109c74daa869d91798848c26b382a14e17c (patch) | |
tree | 6eb4ee77da1524ae16ba114cc084c96c13bb73b2 /2021/day9/src/main.rs | |
parent | bf16b19b1f6deffd1983efca059db576f3b60ee5 (diff) | |
download | aoc-4f913109c74daa869d91798848c26b382a14e17c.tar.gz aoc-4f913109c74daa869d91798848c26b382a14e17c.tar.bz2 aoc-4f913109c74daa869d91798848c26b382a14e17c.zip |
2021, day9: part1
Diffstat (limited to '2021/day9/src/main.rs')
-rw-r--r-- | 2021/day9/src/main.rs | 67 |
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 @@ | |||
1 | use std::env; | ||
2 | use std::fs::File; | ||
3 | use std::io::{BufRead, BufReader}; | ||
4 | |||
5 | fn 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 | |||
55 | fn 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 | } | ||