summaryrefslogtreecommitdiff
path: root/aoc22/day3/src/main.rs
blob: 81a3fe7b9ae56eff80170364a1d4752f97b389b4 (plain) (blame)
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
#![feature(iter_next_chunk)]

use std::collections::HashSet;

fn main() {
    part1();
    part2();
}

fn part1() {
    let input = include_str!("../input");

    let ans: u32 = input.lines().map(|line| {
        let first = &line[..line.len()/2];
        let second = &line[line.len()/2..];
        let first: HashSet<char> = first.chars().collect();
        let second: HashSet<char> = second.chars().collect();
        let common = *first.intersection(&second).next().unwrap();
        let priority = match common {
            'a'..='z' => 1 + common as u32 - 'a' as u32,
            'A'..='Z' => 27 + common as u32 - 'A' as u32,
            _ => unreachable!(),
        };

        priority
    }).sum();

    println!("{}", ans);
}

fn part2() {
    let input = include_str!("../input");

    let mut lines = input.lines();

    let mut sum = 0;
    while let Ok([first, second, third]) = lines.next_chunk::<3>() {
        let first: HashSet<char> = first.chars().collect();
        let second: HashSet<char> = second.chars().collect();
        let third: HashSet<char> = third.chars().collect();
        let common = *first
            .intersection(&second)
            .copied()
            .collect::<HashSet<char>>()
            .intersection(&third)
            .next()
            .unwrap();

        let priority = match common {
            'a'..='z' => 1 + common as u32 - 'a' as u32,
            'A'..='Z' => 27 + common as u32 - 'A' as u32,
            _ => unreachable!(),
        };

        sum += priority;
    }

    println!("{}", sum);
}