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
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let reader = open_file();
let points = HashMap::from([(')', 3), (']', 57), ('}', 1197), ('>', 25137)]);
let comp_points = HashMap::from([(')', 1), (']', 2), ('}', 3), ('>', 4)]);
let pairs = HashMap::from([('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')]);
let opening = vec!['(', '[', '{', '<'];
let closing = vec![')', ']', '}', '>'];
let mut final_scores = Vec::new();
let mut score = 0;
for line in reader.lines() {
let mut stack: Vec<char> = Vec::new();
let mut flag = false;
if let Ok(ln) = line {
for char in ln.chars() {
if opening.contains(&char) {
stack.push(char);
} else if closing.contains(&char) {
let t = stack.pop().unwrap();
if char == *pairs.get(&t).unwrap() {
} else {
score += points.get(&char).unwrap();
flag = true;
break;
}
}
}
if !flag {
let mut score: u64 = 0;
stack.reverse();
for c in &stack {
score *= 5;
score += comp_points.get(pairs.get(c).unwrap()).unwrap();
}
final_scores.push(score);
}
}
}
final_scores.sort_unstable();
let idx = final_scores.len() / 2;
println!("part 1: {}", score);
println!("part 2: {}", final_scores[idx]);
}
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)
}
|