summaryrefslogtreecommitdiff
path: root/03/src/part-2.rs
blob: e3cda54fc3d3ee9e2687e6768fcbf9e4a75fc250 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use std::io::{BufRead};

const GROUP_SIZE: usize = 3;

fn main() {    
    let stdin = std::io::stdin();
    let mut handle = stdin.lock();
    
    let all_ones: u64 = {
        let mut ret: u64 = 0;
        for i in 0..64 {
            ret |= 1 << i;
        }
        ret
    };

    let mut result: usize = 0;
    let mut buf: Vec<u8> = Vec::new();
    let mut done: bool = false;
    
    loop {
        let mut set: u64 = all_ones;

        for i in 0..GROUP_SIZE {
            buf.clear();
            let num_bytes = handle.read_until(b'\n', &mut buf).expect("IO error");
            if num_bytes == 0 {
                if i == 0 {
                    done = true;
                    break;
                }
                else { panic!("Malformed input"); }
            }

            let stripped_buf: & [u8] = {
                if buf[buf.len() - 1] == b'\n' {
                    & buf[0..buf.len()-1]
                }
                else {
                    & buf
                }
            };

            assert!(!stripped_buf.is_empty());

            let mut seen: u64 = 0;
            
            for &c in stripped_buf {
                assert!((c >= 65 && c <= 90) || (c >= 97 && c <= 122));
                if c <= 90 {
                    seen |= 1 << (c - b'A');
                }
                else {
                    seen |= 1 << (c - b'a' + 26);
                }
            }
            set &= seen;
        }

        if done { break; }

        assert_eq!(set.count_ones(), 1);

        for i in 0..26 {
            if set & (1 << i) != 0 {
                result += 26 + i + 1;
                break;
            }
            if set & (1 << (26 + i)) != 0 {
                result += i + 1;
                break;
            }
        }
    }
    println!("{}", result);
}