-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution_2020_06.rs
51 lines (41 loc) · 1.44 KB
/
solution_2020_06.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
use std::collections::HashSet;
fn parse_multi_line(input: &str) -> Vec<Vec<&str>> {
input
.split("\n\n")
.map(|x| x.lines().collect::<Vec<_>>())
.collect::<Vec<_>>()
}
type Answer = char;
type Form = HashSet<Answer>;
type Group = Vec<Form>;
type MergeFunction<T> = fn(HashSet<T>, other: HashSet<T>) -> HashSet<T>;
#[allow(clippy::ptr_arg)]
fn merge_group(group: &Vec<HashSet<Answer>>, f: MergeFunction<Answer>) -> HashSet<Answer> {
group.clone().into_iter().reduce(f).unwrap_or_default()
}
fn solve(groups: &[Group], f: MergeFunction<Answer>) -> usize {
groups.iter().map(|g| merge_group(g, f).len()).sum()
}
#[allow(clippy::needless_for_each)]
fn main() {
let raw_data = include_str!("../../resources/06.txt");
let groups: Vec<Group> = parse_multi_line(raw_data)
.into_iter()
.map(|x| {
x.into_iter()
.map(|s| s.chars().collect::<HashSet<Answer>>())
.collect()
})
.collect();
let union: MergeFunction<Answer> = |a: HashSet<Answer>, b: HashSet<Answer>| {
HashSet::union(&a, &b).copied().collect::<HashSet<Answer>>()
};
let intersection: MergeFunction<Answer> = |a: HashSet<Answer>, b: HashSet<Answer>| {
HashSet::intersection(&a, &b)
.copied()
.collect::<HashSet<Answer>>()
};
vec![union, intersection]
.into_iter()
.for_each(|f| println!("{}", solve(&groups, f)));
}