aoc/year2021/day08.rs
1//! # Seven Segment Search
2//!
3//! Listing each digit and the number of segments that are lit when that digit is displayed:
4//!
5//! | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
6//! |---|---|---|---|---|---|---|---|---|---|
7//! | 6 | 2 | 5 | 5 | 4 | 5 | 6 | 3 | 7 | 6 |
8//!
9//! shows that 3 digits share 5 segments and another 3 share 6 segments so we don't have enough
10//! information just yet. Listing the total occurences of each segment summing across all 10 digits:
11//!
12//! | a | b | c | d | e | f | g |
13//! |---|---|---|---|---|---|---|
14//! | 8 | 6 | 8 | 7 | 4 | 9 | 7 |
15//!
16//! shows that 2 segments share 7 occurences and 2 share 8 occurences so this is still not quite enough
17//! information. However if we combine these 2 tables by *summing* the segment occurences for each
18//! digit, for example `1` has segments `c` and `f` for a total of 17, then the table looks like:
19//!
20//! | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
21//! |----|----|----|----|----|----|----|----|----|----|
22//! | 42 | 17 | 34 | 39 | 30 | 37 | 41 | 25 | 49 | 45 |
23//!
24//! Now each digit can be uniquely identified. Our algorithm is as follows:
25//! * Calculate the occurences of each scrambled segment letter before the `|` symbol. Since the
26//! cardinality of the set is fixed, we can use an array instead of a `HashMap` for speed.
27//! * Add the occurences of each scrambled segment for each digit after the `|` symbol, then
28//! lookup the total and map directly to the unscrambled digit.
29use crate::util::iter::*;
30use crate::util::slice::*;
31
32type Input = Vec<[u32; 4]>;
33
34pub fn parse(input: &str) -> Input {
35 input.lines().map(descramble).collect()
36}
37
38pub fn part1(input: &Input) -> usize {
39 input.iter().flatten().filter(|&&d| d == 1 || d == 4 || d == 7 || d == 8).count()
40}
41
42pub fn part2(input: &Input) -> u32 {
43 input.iter().map(|digits| digits.fold_decimal()).sum()
44}
45
46fn descramble(line: &str) -> [u32; 4] {
47 let mut frequency = [0_u8; 104];
48 let bytes = line.as_bytes();
49 bytes[0..58].iter().for_each(|&b| frequency[b as usize] += 1);
50 bytes[61..]
51 .split(|&b| b == b' ')
52 .map(|scrambled| to_digit(scrambled.iter().map(|&b| frequency[b as usize]).sum()))
53 .chunk::<4>()
54 .next()
55 .unwrap()
56}
57
58fn to_digit(total: u8) -> u32 {
59 match total {
60 42 => 0,
61 17 => 1,
62 34 => 2,
63 39 => 3,
64 30 => 4,
65 37 => 5,
66 41 => 6,
67 25 => 7,
68 49 => 8,
69 45 => 9,
70 _ => unreachable!(),
71 }
72}