diff options
author | Yigit Sever | 2021-12-20 16:56:51 +0300 |
---|---|---|
committer | Yigit Sever | 2021-12-20 16:56:51 +0300 |
commit | ca60384d831d1208227b3538ca121ebc4624b0f2 (patch) | |
tree | fae54d59ecd77c513ba149e9c89e72e6d368720d /2021/day10/src | |
parent | 3621b8231a603854e6c088df2879bae02e62681d (diff) | |
download | aoc-ca60384d831d1208227b3538ca121ebc4624b0f2.tar.gz aoc-ca60384d831d1208227b3538ca121ebc4624b0f2.tar.bz2 aoc-ca60384d831d1208227b3538ca121ebc4624b0f2.zip |
2021, day10: done
Diffstat (limited to '2021/day10/src')
-rw-r--r-- | 2021/day10/src/main.rs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/2021/day10/src/main.rs b/2021/day10/src/main.rs new file mode 100644 index 0000000..dcb44a8 --- /dev/null +++ b/2021/day10/src/main.rs | |||
@@ -0,0 +1,65 @@ | |||
1 | use std::collections::HashMap; | ||
2 | use std::env; | ||
3 | use std::fs::File; | ||
4 | use std::io::{BufRead, BufReader}; | ||
5 | |||
6 | fn main() { | ||
7 | let reader = open_file(); | ||
8 | let points = HashMap::from([(')', 3), (']', 57), ('}', 1197), ('>', 25137)]); | ||
9 | let comp_points = HashMap::from([(')', 1), (']', 2), ('}', 3), ('>', 4)]); | ||
10 | let pairs = HashMap::from([('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')]); | ||
11 | let opening = vec!['(', '[', '{', '<']; | ||
12 | let closing = vec![')', ']', '}', '>']; | ||
13 | let mut final_scores = Vec::new(); | ||
14 | |||
15 | let mut score = 0; | ||
16 | |||
17 | for line in reader.lines() { | ||
18 | let mut stack: Vec<char> = Vec::new(); | ||
19 | let mut flag = false; | ||
20 | if let Ok(ln) = line { | ||
21 | for char in ln.chars() { | ||
22 | if opening.contains(&char) { | ||
23 | stack.push(char); | ||
24 | } else if closing.contains(&char) { | ||
25 | let t = stack.pop().unwrap(); | ||
26 | if char == *pairs.get(&t).unwrap() { | ||
27 | } else { | ||
28 | score += points.get(&char).unwrap(); | ||
29 | flag = true; | ||
30 | break; | ||
31 | } | ||
32 | } | ||
33 | } | ||
34 | if !flag { | ||
35 | let mut score: u64 = 0; | ||
36 | stack.reverse(); | ||
37 | for c in &stack { | ||
38 | score *= 5; | ||
39 | score += comp_points.get(pairs.get(c).unwrap()).unwrap(); | ||
40 | } | ||
41 | final_scores.push(score); | ||
42 | } | ||
43 | } | ||
44 | } | ||
45 | |||
46 | final_scores.sort_unstable(); | ||
47 | let idx = final_scores.len() / 2; | ||
48 | |||
49 | println!("part 1: {}", score); | ||
50 | println!("part 2: {}", final_scores[idx]); | ||
51 | } | ||
52 | |||
53 | fn open_file() -> BufReader<File> { | ||
54 | let args: Vec<String> = env::args().collect(); | ||
55 | |||
56 | if args.len() != 2 { | ||
57 | eprintln!("Usage: {} <filename>", args[0]); | ||
58 | std::process::exit(1); | ||
59 | } | ||
60 | |||
61 | let filename = &args[1]; | ||
62 | |||
63 | let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename)); | ||
64 | BufReader::new(file) | ||
65 | } | ||