aoc/year2020/day06.rs
1//! # Custom Customs
2//!
3//! This is a disguised binary question like the previous [`day 5`].
4//!
5//! We can store each passenger's answers as an implicit set in a `u32` since the cardinality
6//! is only 26. For each yes answer we set a bit, shifting left based on the letter. For example
7//! `acf` would be represented as `100101`.
8//!
9//! For part one to find groups where any person answered yes, we reduce the group using
10//! [bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation) then count the number of ones
11//! for each group using the blazing fast [`count_ones`] intrinsic.
12//!
13//! Part two is very similar, except that we use a bitwise AND instead.
14//!
15//! [`day 5`]: crate::year2020::day05
16//! [`count_ones`]: u32::count_ones
17
18pub fn parse(input: &str) -> Vec<u32> {
19 input.lines().map(|line| line.bytes().fold(0, |acc, b| acc | (1 << (b - b'a')))).collect()
20}
21
22pub fn part1(input: &[u32]) -> u32 {
23 count_answers(input, u32::MIN, |group, passenger| group | passenger)
24}
25
26pub fn part2(input: &[u32]) -> u32 {
27 count_answers(input, u32::MAX, |group, passenger| group & passenger)
28}
29
30fn count_answers(input: &[u32], initial: u32, combine: fn(u32, u32) -> u32) -> u32 {
31 let mut total = 0;
32 let mut group = initial;
33
34 for &passenger in input {
35 if passenger == 0 {
36 total += group.count_ones();
37 group = initial;
38 } else {
39 group = combine(group, passenger);
40 }
41 }
42
43 total + group.count_ones()
44}