summaryrefslogtreecommitdiff
path: root/10/src/part-2.rs
blob: 76f8a2a44148184eb12985ba4350a72c839a085d (plain)
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
use std::io::{BufRead};

fn num(c: char) -> usize {
    match c {
        '(' => 0,
        '[' => 1,
        '{' => 2,
        '<' => 3,
        ')' => 4,
        ']' => 5,
        '}' => 6,
        '>' => 7,
        _   => panic!("Unknown character: {}", c)
    }
}

pub fn main() {
    let stdin = std::io::stdin();
    let handle = stdin.lock();

    let mut scores: Vec<usize> = Vec::new();
    for l in handle.lines() {
        let line = l.unwrap();
        //println!("{}", line);
        let mut corrupted = false;
        let mut opened: Vec<usize> = Vec::new();
        for c in line.chars() {
            let i = num(c);
            if i < 4 { // Open.
                opened.push(i);
            }
            else { // Close.
                let last_opened = opened.pop().unwrap_or(usize::MAX);
                if i-4 == last_opened { // Valid
                }
                else { // Invalid.
                    corrupted = true;
                    break;
                }                
            }
        }

        if !corrupted {
            //println!("Processing uncorrupted, incomplete line. Got {} opened.", opened.len());
            scores.push(0);
            for i in opened.into_iter().rev() {
                let last_score: &mut usize = scores.last_mut().unwrap();
                *last_score *= 5;
                *last_score += i + 1;
            }
        }
    }

    scores.sort();
    assert!(scores.len() % 2 == 1);
    println!("Score: {}", scores[scores.len() / 2]);
}