85 lines
2.1 KiB
Rust
85 lines
2.1 KiB
Rust
use std::collections::HashSet;
|
|
use std::error::Error;
|
|
use std::fs::File;
|
|
use std::io::{self, BufRead};
|
|
use std::vec::Vec;
|
|
|
|
enum SyntaxPoints {
|
|
Corrupted(u64),
|
|
Incomplete(u64),
|
|
}
|
|
|
|
fn check_syntax(line: &str) -> SyntaxPoints {
|
|
let mut stack: Vec<char> = Vec::new();
|
|
|
|
for c in line.chars() {
|
|
match c {
|
|
'[' => stack.push('['),
|
|
'(' => stack.push('('),
|
|
'{' => stack.push('{'),
|
|
'<' => stack.push('<'),
|
|
']' => {
|
|
if stack.pop() != Some('[') {
|
|
return SyntaxPoints::Corrupted(57);
|
|
}
|
|
}
|
|
')' => {
|
|
if stack.pop() != Some('(') {
|
|
return SyntaxPoints::Corrupted(3);
|
|
}
|
|
}
|
|
'}' => {
|
|
if stack.pop() != Some('{') {
|
|
return SyntaxPoints::Corrupted(1197);
|
|
}
|
|
}
|
|
'>' => {
|
|
if stack.pop() != Some('<') {
|
|
return SyntaxPoints::Corrupted(25137);
|
|
}
|
|
}
|
|
_ => panic!("Unknown char {}", c),
|
|
}
|
|
}
|
|
|
|
let mut points = 0;
|
|
for c in stack.iter().rev() {
|
|
match c {
|
|
'(' => points = points * 5 + 1,
|
|
'[' => points = points * 5 + 2,
|
|
'{' => points = points * 5 + 3,
|
|
'<' => points = points * 5 + 4,
|
|
_ => panic!("Unknown char {}", c),
|
|
}
|
|
}
|
|
|
|
SyntaxPoints::Incomplete(points)
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let file = File::open("inputs/day10.txt")?;
|
|
let lines: Vec<String> = io::BufReader::new(file)
|
|
.lines()
|
|
.map(|l| l.unwrap())
|
|
.collect();
|
|
|
|
let mut answer1 = 0;
|
|
|
|
let mut incompletes: Vec<u64> = Vec::new();
|
|
|
|
for line in lines.iter() {
|
|
match check_syntax(line) {
|
|
SyntaxPoints::Corrupted(p) => answer1 += p,
|
|
SyntaxPoints::Incomplete(p) => incompletes.push(p),
|
|
}
|
|
}
|
|
|
|
println!("Answer1: {}", answer1);
|
|
|
|
incompletes.sort();
|
|
|
|
println!("Answer2: {}", incompletes[incompletes.len() / 2]);
|
|
|
|
Ok(())
|
|
}
|