-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.rs
104 lines (99 loc) · 2.75 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
pub fn part1<'a, I, S>(lines: I) -> u32
where
I: IntoIterator<Item = &'a S>,
S: AsRef<str> + 'a,
{
lines
.into_iter()
.filter_map(|line| {
let mut expected = Vec::new();
for c in line.as_ref().chars() {
if c == '(' {
expected.push(')')
} else if c == '[' {
expected.push(']')
} else if c == '{' {
expected.push('}')
} else if c == '<' {
expected.push('>')
} else if Some(c) == expected.pop() {
} else if c == ')' {
return Some(3);
} else if c == ']' {
return Some(57);
} else if c == '}' {
return Some(1197);
} else if c == '>' {
return Some(25137);
} else {
return None;
}
}
None
})
.sum()
}
pub fn part2<'a, I, S>(lines: I) -> Option<u64>
where
I: IntoIterator<Item = &'a S>,
S: AsRef<str> + 'a,
{
let mut scores = Vec::new();
'outer: for line in lines {
let mut expected = Vec::new();
for c in line.as_ref().chars() {
if c == '(' {
expected.push(')')
} else if c == '[' {
expected.push(']')
} else if c == '{' {
expected.push('}')
} else if c == '<' {
expected.push('>')
} else if Some(c) == expected.pop() {
} else {
continue 'outer;
}
}
scores.push(
expected
.into_iter()
.rev()
.filter_map(|c| match c {
')' => Some(1),
']' => Some(2),
'}' => Some(3),
'>' => Some(4),
_ => None,
})
.fold(0, |acc, x| 5 * acc + x),
);
}
scores.sort_unstable();
scores.get(scores.len() / 2).cloned()
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
static EXAMPLE: &[&str] = &[
"[({(<(())[]>[[{[]{<()<>>",
"[(()[<>])]({[<{<<[]>>(",
"{([(<{}[<>[]}>{[]{[(<()>",
"(((({<>}<{<{<>}{[]{[]{}",
"[[<[([]))<([[{}[[()]]]",
"[{[{({}]{}}([{[{{{}}([]",
"{<[[]]>}<{[{[{[]{()[[[]",
"[<(<(<(<{}))><([]([]()",
"<{([([[(<>()){}]>(<<{{",
"<{([{{}}[<[[[<>{}]]]>[]]",
];
#[test]
fn part1_examples() {
assert_eq!(26397, part1(EXAMPLE));
}
#[test]
fn part2_examples() {
assert_eq!(Some(288957), part2(EXAMPLE));
}
}