-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_10.rs
109 lines (92 loc) · 2.59 KB
/
day_10.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
use common::{Answer, Solution};
const CHARS: [(char, char); 4] = [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')];
pub struct Day10;
impl Solution for Day10 {
fn name(&self) -> &'static str {
"Syntax Scoring"
}
fn part_a(&self, input: &str) -> Answer {
let data = parse(input);
let mut total = 0;
for i in data {
let mut closeing = Vec::new();
for j in i.chars() {
if char_contains_key(j) {
closeing.push(char_for_char(j));
continue;
}
if closeing.is_empty() || j != closeing.pop().unwrap() {
total += match j {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
_ => unreachable!(),
};
break;
}
}
}
total.into()
}
fn part_b(&self, input: &str) -> Answer {
let data = parse(input);
let mut scores = Vec::new();
for i in data {
let mut queue = Vec::new();
let mut is_corrupted = false;
for j in i.chars() {
if char_contains_key(j) {
queue.push(char_for_char(j));
continue;
}
if queue.is_empty() || j != queue.pop().unwrap() {
is_corrupted = true;
break;
}
}
if !is_corrupted {
let mut score = 0;
while let Some(ch) = queue.pop() {
score = 5 * score
+ match ch {
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
_ => unreachable!(),
};
}
scores.push(score);
}
}
scores.sort_unstable();
let mid = scores.len() / 2;
scores[mid].into()
}
}
fn parse(lines: &str) -> Vec<String> {
lines
.lines()
.map(|x| x.to_string())
.collect::<Vec<String>>()
}
fn char_for_char(inp: char) -> char {
for i in CHARS {
if i.0 == inp {
return i.1;
}
if i.1 == inp {
return i.0;
}
}
unreachable!()
}
fn char_contains_key(inp: char) -> bool {
for i in CHARS {
if i.0 == inp {
return true;
}
}
false
}