-
Notifications
You must be signed in to change notification settings - Fork 0
/
day03.rs
62 lines (53 loc) · 1.74 KB
/
day03.rs
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
use std::collections::HashSet;
use itertools::Itertools;
use crate::utils::v2::solver;
pub struct Solver;
impl Solver {
const PRIORITIES: &'static str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
fn get_priority(c: char) -> usize {
// O(n), but pretty self-explanatory and avoids ASCII manipulation.
Solver::PRIORITIES.find(c).unwrap() + 1
}
fn intersect(sets: (HashSet<char>, HashSet<char>, HashSet<char>)) -> char {
let (a, b, c) = sets;
a.intersection(&b)
.cloned()
.collect::<HashSet<_>>()
.intersection(&c)
.next()
.unwrap()
.clone()
}
}
impl solver::Solver<2022, 3> for Solver {
type Part1 = usize;
type Part2 = usize;
fn solve_part_one(&self, input: &str) -> Self::Part1 {
input
.trim()
.lines()
.map(|l| {
(
l[0..l.len() / 2].chars().collect::<HashSet<_>>(),
l[l.len() / 2..].chars().collect::<HashSet<_>>(),
)
})
.map(|(a, b)| a.intersection(&b).next().unwrap().clone())
.map(|intersection| Solver::get_priority(intersection))
.sum()
}
fn solve_part_two(&self, input: &str) -> Self::Part2 {
let groups = input.trim().lines().chunks(3);
groups
.into_iter()
.map(|group| {
group
.map(|elf| elf.chars().collect::<HashSet<_>>())
.collect_tuple::<(_, _, _)>()
.unwrap()
})
.map(|elves| Solver::intersect(elves))
.map(|intersection| Solver::get_priority(intersection))
.sum()
}
}