70 %
Chris Biscardi

Advent of Code 2020 in Rust day 6: fold_first HashSets

Part 1: find the unique characters for each group in this input. sum the counts.

abc
a
b
c
ab
ac
a
a
a
a
b

HashSets make this fairly easy to implement. Given an iterator over chars, we can filter out newlines (which are chars we don't want included) and collect into a HashSet<char>, then sum them all.

part-1.rs
rust
pub fn process_part1(input: &str) -> usize {
input
.split("\n\n")
.map(|lines| {
lines
.chars()
.filter(|v| *v != '\n')
.collect::<HashSet<char>>()
.len()
})
.sum()
}

Part 2 requires that you count only the characters that appear in every line. We can still take advantage of HashSet but the intersection function on HashSet only operates on two sets at a time 😱 , so we can use the nightly offered fold_first and some cloning to apply it to all of the sets.

rust
pub fn process_part2(input: &str) -> usize {
input
.split("\n\n")
.filter_map(|lines| {
lines
.split('\n')
.map(|line| line.chars().collect::<HashSet<char>>())
.fold_first(|acc, v| acc.intersection(&v).cloned().collect())
.map(|m| m.len())
})
.sum()
}