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 let mut total = 0;
24 let mut group = u32::MIN;
25
26 for &passenger in input {
27 if passenger == 0 {
28 total += group.count_ones();
29 group = u32::MIN;
30 } else {
31 group |= passenger;
32 }
33 }
34
35 total + group.count_ones()
36}
37
38pub fn part2(input: &[u32]) -> u32 {
39 let mut total = 0;
40 let mut group = u32::MAX;
41
42 for &passenger in input {
43 if passenger == 0 {
44 total += group.count_ones();
45 group = u32::MAX;
46 } else {
47 group &= passenger;
48 }
49 }
50
51 total + group.count_ones()
52}