summary refs log tree commit diff
path: root/10/src/main.rs
blob: 35fbf714c3b803c8abbca7b33f901bfa8237f4a4 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use advent_lib::prelude::*;


fn main() -> Result<()> {
  let mut args = std::env::args();
  if args.len() != 2 {
    eprintln!("Usage: advent input");
  }
  let _ = args.next();
  let filename = args.next().unwrap();

  let input = advent_lib::read_lines_file(&filename)?;

  let mut total_score = 0;
  let mut incomplete_lines = Vec::new();
  for line in &input {
    let mut chars = line.chars().peekable();
    let score = parse(&mut chars);
    total_score += score;

    if score == 0 {
      incomplete_lines.push(line.clone());
    }
  }
  println!("{}", total_score);

  let mut completion_scores = Vec::new();
  for line in &incomplete_lines {
    let mut chars = line.chars().peekable();
    let completion = repair(&mut chars, true).unwrap();
    let mut score: i64 = 0;
    for c in completion.chars() {
      score *= 5;
      score += match c {
        ')' => 1,
        ']' => 2,
        '}' => 3,
        '>' => 4,
        _ => 0,
      }
    }
    completion_scores.push(score);
  }
  completion_scores.sort();
  let second_score = completion_scores[completion_scores.len() / 2];
  println!("{}", second_score);

  Ok(())
}


fn parse(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> i64 {
  match chars.next() {
    None => {
      return 0;
    }
    Some(open) => {
      let open = open.clone();
      loop {
        match chars.peek() {
          None => {
            return 0;
          }
          Some(c) => {
            let c = *c;
            if "([{<".contains(|d| c == d) {
              let score = parse(chars);
              if score != 0 {
                return score;
              }
            } else {
              let _ = chars.next();
              match (open, c) {
                ('(', ')') => { return 0; }
                ('[', ']') => { return 0; }
                ('{', '}') => { return 0; }
                ('<', '>') => { return 0; }
                (_, ')') => { return 3; }
                (_, ']') => { return 57; }
                (_, '}') => { return 1197; }
                (_, '>') => { return 25137; }
                _ => { }
              }
            }
          }
        }
      }
    }
  }
}


fn repair(chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
    is_top_level: bool)
  -> Option<String>
{
  loop {
    match chars.next() {
      None => {
        return Some(String::new());
      }
      Some(open) => {
        let open = open.clone();
        loop {
          match chars.peek() {
            None => {
              let mut result = String::new();
              result.push(match open {
                '(' => ')',
                '[' => ']',
                '{' => '}',
                '<' => '>',
                _ => panic!("alas"),
              });
              return Some(result);
            }
            Some(c) => {
              let c = *c;
              if "([{<".contains(|d| c == d) {
                match repair(chars, false) {
                  None => { }
                  Some(mut result) => {
                    result.push(match open {
                      '(' => ')',
                      '[' => ']',
                      '{' => '}',
                      '<' => '>',
                      _ => panic!("alas"),
                    });
                    return Some(result);
                  }
                }
              } else {
                let _ = chars.next();
                if is_top_level {
                  break;
                } else {
                  return None;
                }
              }
            }
          }
        }
      }
    }
  }
}