Part 1: find the unique characters for each group in this input. sum the counts.
abcabcabacaaaab
HashSet
s make this fairly easy to implement. Given an iterator over char
s, we can filter out newlines (which are chars we don't want included) and collect
into a HashSet<char>
, then sum
them all.
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.
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()}