From 62d5e5b6c0e0936bf8962869fd01e1df0790466b Mon Sep 17 00:00:00 2001 From: Antoine Martin Date: Sun, 6 Dec 2020 13:02:21 +0100 Subject: [PATCH] 2020: day06: cleanup --- aoc2020/src/day06.rs | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/aoc2020/src/day06.rs b/aoc2020/src/day06.rs index fc58c5b..c7db5a5 100644 --- a/aoc2020/src/day06.rs +++ b/aoc2020/src/day06.rs @@ -41,12 +41,7 @@ fn part1(input: &str) -> aoc::Result { Ok(groups .iter() - .map(|group| { - group.answers.iter().fold(HashSet::new(), |set, answers| { - set.union(answers).copied().collect() - }) - }) - .map(|set| set.len()) + .map(|group| group.unique_positive_answers().len()) .sum()) } @@ -55,16 +50,7 @@ fn part2(input: &str) -> aoc::Result { Ok(groups .iter() - .map(|group| { - group - .answers - .iter() - .skip(1) - .fold(group.answers[0].clone(), |set, answers| { - set.intersection(answers).copied().collect() - }) - }) - .map(|set| set.len()) + .map(|group| group.common_positive_answers().len()) .sum()) } @@ -72,6 +58,23 @@ struct Group { answers: Vec>, } +impl Group { + fn unique_positive_answers(&self) -> HashSet { + self.answers.iter().fold(HashSet::new(), |set, answers| { + set.union(answers).copied().collect() + }) + } + + fn common_positive_answers(&self) -> HashSet { + self.answers + .iter() + .skip(1) + .fold(self.answers[0].clone(), |set, answers| { + set.intersection(answers).copied().collect() + }) + } +} + #[cfg(test)] mod tests { use super::*;