Skip to main content

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 `1001010`.
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. It is faster to run
14//! both parts at once during the parse.
15//!
16//! [`day 5`]: crate::year2020::day05
17//! [`count_ones`]: u32::count_ones
18type Input = (u32, u32);
19
20pub fn parse(input: &str) -> Input {
21    let mut any = 0_u32;
22    let mut all = u32::MAX;
23    let mut passenger = 0;
24    let mut part_one = 0;
25    let mut part_two = 0;
26    let mut check_group = false;
27
28    // End the input with a double newline, to include last group in the total.
29    for ch in input.bytes().chain(*b"\n") {
30        match ch {
31            b'\n' if check_group => {
32                // A second newline ends one group and prepares for the next.
33                check_group = false;
34                part_one += any.count_ones();
35                part_two += all.count_ones();
36                any = 0;
37                all = u32::MAX;
38            }
39            b'\n' => {
40                // A single newline separates passengers within a group.
41                any |= passenger;
42                all &= passenger;
43                passenger = 0;
44                check_group = true;
45            }
46            _ => {
47                // A letter sets the next bit for the given passenger.
48                // Masking to bits 1-26 is more efficient than subtracting to bits 0-25.
49                check_group = false;
50                passenger |= 1 << (ch & 0x1f);
51            }
52        }
53    }
54
55    (part_one, part_two)
56}
57
58pub fn part1(input: &Input) -> u32 {
59    input.0
60}
61
62pub fn part2(input: &Input) -> u32 {
63    input.1
64}