summary refs log tree commit diff
path: root/06/src/main.rs
blob: c0045e094b4b5c9678dad42e2070edf02447cf6a (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
use advent_lib::prelude::*;

use std::collections::BTreeSet;


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 groups = advent_lib::group_lines_by_blanks(input);

  let mut unioned_sum = 0;

  for group in &groups {
    let mut yes_answers = BTreeSet::new();

    for line in group {
      for c in line.trim().chars() {
        yes_answers.insert(c);
      }
    }

    unioned_sum += yes_answers.len();
  }

  println!("{}", unioned_sum);

  let mut intersected_sum = 0;

  for group in &groups {
    let mut group_answers = BTreeSet::new();
    let mut is_first_person = true;

    for line in group {
      let mut person_answers = BTreeSet::new();

      for c in line.trim().chars() {
        person_answers.insert(c);
      }

      if is_first_person {
        group_answers = person_answers;
        is_first_person = false;
      } else {
        let mut intersected_answers = BTreeSet::new();
        for c in group_answers.intersection(&person_answers) {
          intersected_answers.insert(c.clone());
        }
        group_answers = intersected_answers;
      }
    }

    intersected_sum += group_answers.len();
  }

  println!("{}", intersected_sum);

  Ok(())
}