Skip to content

Commit dc65f69

Browse files
author
mflinn-broad
committed
finish part 2
1 parent 4094785 commit dc65f69

File tree

1 file changed

+73
-2
lines changed

1 file changed

+73
-2
lines changed

src/days/day10.rs

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
1+
use itertools::Itertools;
2+
13
use crate::util;
24
use std::collections::HashMap;
35

46
pub fn run() {
57
let raw_input = util::read_input("inputs/day10.txt").unwrap();
68
let input = process(&raw_input);
79

8-
println!("Part 1: {:?}", part_1(input));
10+
println!("Part 1: {:?}", part_1(&input));
11+
println!("Part 2: {:?}", part_2(&input));
912
}
1013

1114
fn process(input: &str) -> Vec<Vec<char>> {
1215
input.lines().map(|line| line.chars().collect()).collect()
1316
}
1417

15-
fn part_1(input: Vec<Vec<char>>) -> usize {
18+
fn part_1(input: &Vec<Vec<char>>) -> usize {
1619
let mut error_tracker: HashMap<char, usize> = HashMap::new();
1720
input.iter().for_each(|line| {
1821
let mut stack: Vec<char> = Vec::new();
@@ -44,3 +47,71 @@ fn part_1(input: Vec<Vec<char>>) -> usize {
4447
_ => panic!("unreachable"),
4548
})
4649
}
50+
51+
fn part_2(input: &Vec<Vec<char>>) -> usize {
52+
// remove corrupted and complete lines
53+
let completion_scores: Vec<usize> = input
54+
.iter()
55+
.fold(Vec::new(),|mut completions, line| {
56+
let mut stack: Vec<char> = Vec::new();
57+
for symbol in line {
58+
match symbol {
59+
'(' => stack.push(')'),
60+
'[' => stack.push(']'),
61+
'{' => stack.push('}'),
62+
'<' => stack.push('>'),
63+
x if *x == stack[stack.len() - 1] => {
64+
stack.pop();
65+
}
66+
_ => {
67+
return completions;
68+
}
69+
}
70+
}
71+
if stack.len() == 0 {
72+
completions
73+
} else {
74+
completions.push(stack);
75+
completions
76+
}
77+
})
78+
.iter()
79+
.map(|completion| {
80+
completion.iter().rev().fold(0, |score, symbol| match symbol {
81+
')' => (score * 5) + 1,
82+
']' => (score * 5) + 2,
83+
'}' => (score * 5) + 3,
84+
'>' => (score * 5) + 4,
85+
_ => panic!("unreachable"),
86+
})
87+
})
88+
.sorted()
89+
.collect();
90+
91+
completion_scores[completion_scores.len() / 2]
92+
}
93+
94+
#[cfg(test)]
95+
mod tests {
96+
use super::*;
97+
extern crate test;
98+
use test::Bencher;
99+
100+
#[bench]
101+
fn bench_part_1(b: &mut Bencher) {
102+
let raw_input = util::read_input("inputs/day10.txt").unwrap();
103+
b.iter(|| {
104+
let mut input = process(&raw_input);
105+
part_1(&mut input);
106+
});
107+
}
108+
109+
#[bench]
110+
fn bench_part_2(b: &mut Bencher) {
111+
let raw_input = util::read_input("inputs/day10.txt").unwrap();
112+
b.iter(|| {
113+
let input = process(&raw_input);
114+
part_2(&input);
115+
});
116+
}
117+
}

0 commit comments

Comments
 (0)