DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 6: Custom Customs

Collapse
 
ballpointcarrot profile image
Christopher Kruse

Ugh, made it too late for this day (but I had it done in time for the problem, honest!).

Used HashSet to my benefit here, as I could apply set theory to the problem and get it done easily.

As always, in Github.

use aoc_runner_derive::{aoc, aoc_generator};
use std::collections::HashSet;

#[aoc_generator(day6)]
fn parse_input_day6(input: &str) -> Vec<String> {
    input
        .split("\n\n")
        .map(|group| String::from(group))
        .collect()
}

#[aoc(day6, part1)]
fn sum_group_questions(input: &Vec<String>) -> usize {
    let answers: Vec<HashSet<char>> = input
        .iter()
        .map(|group| group.chars().filter(|x| *x != '\n').collect())
        .collect();
    answers.iter().map(|group| group.len()).sum()
}

#[aoc(day6, part2)]
fn sum_group_common_questions(input: &Vec<String>) -> usize {
    input
        .iter()
        .map(|group| {
            let mut first_run = true;
            group
                .lines()
                .map(|answers| answers.chars().collect::<HashSet<char>>())
                .fold(HashSet::new(), |memo, ans| {
                    if memo.is_empty() && first_run {
                        first_run = false;
                        ans.clone()
                    } else {
                        let intersect = memo.intersection(&ans).cloned().collect();
                        intersect
                    }
                })
                .len()
        })
        .sum()
}
Enter fullscreen mode Exit fullscreen mode