-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.rs
118 lines (109 loc) · 2.86 KB
/
day10.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use aoc_runner_derive::{aoc, aoc_generator};
type Parsed = Vec<String>;
#[aoc_generator(day10)]
fn parse_input(input: &str) -> Parsed {
input.lines().map(|l| l.to_owned()).collect()
}
#[aoc(day10, part1)]
fn part1(input: &Parsed) -> u128 {
input.iter().map(count_points_if_corrupted).sum()
}
#[aoc(day10, part2)]
fn part2(input: &Parsed) -> u128 {
let mut points: Vec<u128> = input
.iter()
.filter(|l| count_points_if_corrupted(l) == 0)
.map(|l| {
let mut queue = vec![];
for c in l.chars() {
match c {
'(' => queue.push(0),
'[' => queue.push(1),
'{' => queue.push(2),
'<' => queue.push(3),
')' => {
queue.pop();
}
']' => {
queue.pop();
}
'}' => {
queue.pop();
}
'>' => {
queue.pop();
}
_ => unreachable!(),
};
}
queue.iter().rev().fold(0, |a, q| a * 5 + q + 1)
})
.collect();
points.sort_unstable();
points[points.len() / 2]
}
fn count_points_if_corrupted(l: &String) -> u128 {
let mut queue = vec![];
for c in l.chars() {
match c {
'(' => queue.push(0),
'[' => queue.push(1),
'{' => queue.push(2),
'<' => queue.push(3),
')' => {
if let Some(q) = queue.pop() {
if q != 0 {
return 3;
}
}
}
']' => {
if let Some(q) = queue.pop() {
if q != 1 {
return 57;
}
}
}
'}' => {
if let Some(q) = queue.pop() {
if q != 2 {
return 1197;
}
}
}
'>' => {
if let Some(q) = queue.pop() {
if q != 3 {
return 25137;
}
}
}
_ => unreachable!(),
};
}
0
}
#[cfg(test)]
mod tests {
use super::*;
fn input<'a>() -> &'a str {
"[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]"
}
#[test]
fn sample1() {
assert_eq!(part1(&parse_input(input())), 26397);
}
#[test]
fn sample2() {
assert_eq!(part2(&parse_input(input())), 288957);
}
}