-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
98 lines (91 loc) · 2.28 KB
/
main.rs
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
fn open_to_close(c: char) -> char {
match c {
'(' => ')',
'[' => ']',
'{' => '}',
'<' => '>',
_ => panic!(),
}
}
fn check_corrupt(line: &str) -> Option<char> {
let mut stack = vec![];
for char in line.chars() {
match char {
'(' | '[' | '{' | '<' => stack.push(char),
closing => {
if let Some(last_open) = stack.pop() {
if open_to_close(last_open) != closing {
return Some(closing);
}
} else {
panic!("unexpected empty stack");
}
}
}
}
None
}
fn part1(input: &str) -> usize {
input
.lines()
.filter_map(check_corrupt)
.map(|c| match c {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
_ => panic!(),
})
.sum()
}
fn incomplete_score(line: &str) -> Option<usize> {
let mut stack = vec![];
for char in line.chars() {
match char {
'(' | '[' | '{' | '<' => stack.push(char),
closing => {
if let Some(last_open) = stack.pop() {
if open_to_close(last_open) != closing {
return None;
}
} else {
panic!("unexpected empty stack");
}
}
}
}
Some(
stack
.iter()
.map(|&c| open_to_close(c))
.map(|c| match c {
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
_ => panic!(),
})
.rev()
.fold(0, |score, cur| score * 5 + cur),
)
}
fn part2(input: &str) -> usize {
let mut scores = input
.lines()
.filter_map(incomplete_score)
.collect::<Vec<_>>();
scores.sort();
*scores.get(scores.len() / 2).unwrap()
}
fn main() {
println!("Part 1: {}", part1(include_str!("in.txt")));
println!("Part 2: {}", part2(include_str!("in.txt")));
}
#[test]
fn test_part1() {
assert_eq!(part1(include_str!("test.txt")), 26397);
}
#[test]
fn test_part2() {
assert_eq!(part2(include_str!("test.txt")), 288957);
}