Skip to content

Instantly share code, notes, and snippets.

@neofight78
Last active December 10, 2021 09:14
Show Gist options
  • Save neofight78/bac83a39407009bff70886e2286c9313 to your computer and use it in GitHub Desktop.
Save neofight78/bac83a39407009bff70886e2286c9313 to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 10: Syntax Scoring
fn parse(subsystem: Vec<Vec<char>>) -> u64 {
subsystem
.iter()
.map(|line| {
if let (Some(c), _) = check_line(line) {
match c {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
_ => panic!("Invalid token!"),
}
} else {
0
}
})
.sum()
}
fn autocomplete(subsystem: Vec<Vec<char>>) -> u64 {
let mut scores = subsystem
.iter()
.map(|line| check_line(line))
.filter(|(error, _)| error.is_none())
.map(|(_, stack)| {
stack.iter().rev().fold(0, |total, &c| {
total * 5
+ match c {
'(' => 1,
'[' => 2,
'{' => 3,
'<' => 4,
_ => panic!("Invalid token!"),
}
})
})
.collect::<Vec<_>>();
scores.sort_unstable();
scores[scores.len() / 2]
}
fn check_line(line: &[char]) -> (Option<char>, Vec<char>) {
let mut stack = Vec::new();
for &c in line {
match c {
'(' | '[' | '{' | '<' => stack.push(c),
_ => match stack.pop().unwrap() {
'(' if c == ')' => continue,
'[' if c == ']' => continue,
'{' if c == '}' => continue,
'<' if c == '>' => continue,
_ => return (Some(c), stack),
},
}
}
(None, stack)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment