aoc/year2020/day19.rs
1//! # Monster Messages
2//!
3//! Parsing the input has some nuances. Rust doesn't like recursive structs without indirection,
4//! so for non-leaf rules we keep the rule number in order to lazily lookup the rule in a `vec`
5//! later. This also handles parsing the rules in any order, as a rule may refer to another that
6//! has not been parsed yet.
7//!
8//! My input created 2²¹ or 2097152 total valid matching sequences so trying to generate all
9//! possibilities up front is much slower.
10//!
11//! ## Part One
12//!
13//! The `check` function implements a recursive matcher. If a rule is a prefix of the message
14//! then the function returns `Some(index)` where `index` is the first character *after* the
15//! matching pattern, in order to allow matching to continue with the next rule.
16//! If there is no match then the function returns `None`. For example:
17//!
18//! | Rule | Message | Result |
19//! | ------ | --------- | --------- |
20//! | `aaaa` | `aaaab` | `Some(4)` |
21//! | `aa` | `aaaab` | `Some(2)` |
22//! | `bb` | `aaaab` | `None` |
23//!
24//! As rule 0 must match the *entire* message with no characters left over, we count only messages
25//! with a result of `Some(len)` where `len` is the length of the complete message.
26//!
27//! ## Part Two
28//!
29//! First we do some detective work analyzing the new rules. Rule 8 is:
30//! ```none
31//! 8: 42 | 42 8
32//! ```
33//! This matches one or more repeated rule `42`s (in regex format this would be something like
34//! `42+`).
35//!
36//! Rule 11 is:
37//! ```none
38//! 11: 42 31 | 42 11 31
39//! ```
40//! This matches one or more nested pairs of rule 42 and 31, for example `42 31` or `42 42 31 31`.
41//!
42//! Assuming rule 0 is the same for all inputs:
43//! ```none
44//! 0: 8 11
45//! ```
46//! gives a pattern that matches:
47//! 1. A sequence of two or more rule `42`.
48//! 2. Followed by a sequence of one or more rule `31`.
49//! 3. As long as the number of `42` matches is at least one greater than the number of `31`
50//! matches.
51//!
52//! For example `42 42 31` or `42 42 42 31` or `42 42 42 31 31` matches but *not* `42 42 31 31`.
53//!
54//! Since we don't need to handle the general input case (a common pattern in Advent of Code) we can
55//! implement this rule directly in code.
56use std::iter::successors;
57
58use self::Rule::*;
59use crate::util::parse::*;
60
61type Input<'a> = (Vec<Rule>, Vec<&'a [u8]>);
62
63#[derive(Clone, Copy)]
64pub enum Rule {
65 Letter(u8),
66 Follow(usize),
67 Choice(usize, usize),
68 Sequence(usize, usize),
69 Compound(usize, usize, usize, usize),
70}
71
72pub fn parse(input: &str) -> Input<'_> {
73 let (prefix, suffix) = input.split_once("\n\n").unwrap();
74 let mut tokens = Vec::new();
75 let mut rules = vec![Letter(0); 640]; // 640 rules ought to be enough for anybody.
76
77 for line in prefix.lines() {
78 tokens.extend(line.iter_unsigned::<usize>());
79 rules[tokens[0]] = match tokens[1..] {
80 [] if line.contains('a') => Letter(b'a'),
81 [] => Letter(b'b'),
82 [a] => Follow(a),
83 [a, b] if line.contains('|') => Choice(a, b),
84 [a, b] => Sequence(a, b),
85 [a, b, c, d] => Compound(a, b, c, d),
86 _ => unreachable!(),
87 };
88 tokens.clear();
89 }
90
91 let messages = suffix.lines().map(str::as_bytes).collect();
92 (rules, messages)
93}
94
95pub fn part1(input: &Input<'_>) -> usize {
96 let (rules, messages) = input;
97 messages.iter().filter(|message| check(rules, 0, message, 0) == Some(message.len())).count()
98}
99
100pub fn part2(input: &Input<'_>) -> usize {
101 let (rules, messages) = input;
102 messages
103 .iter()
104 .filter(|message| {
105 // Count consecutive matches of a rule, also returning the index after the last match.
106 let repeat = |rule, start| {
107 successors(Some(start), |&index| check(rules, rule, message, index))
108 .enumerate()
109 .last()
110 .unwrap()
111 };
112
113 let (first, index) = repeat(42, 0);
114 let (second, index) = if first >= 2 { repeat(31, index) } else { (0, index) };
115
116 index == message.len() && 1 <= second && second < first
117 })
118 .count()
119}
120
121fn check(rules: &[Rule], rule: usize, message: &[u8], index: usize) -> Option<usize> {
122 // Convenience closures help shorten the expressions in the match block.
123 // The compiler usually inlines short closures so these should have no effect on performance.
124 let apply = |a| check(rules, a, message, index);
125 let sequence = |a, b| apply(a).and_then(|next| check(rules, b, message, next));
126
127 match rules[rule] {
128 Letter(l) => (message.get(index) == Some(&l)).then_some(index + 1),
129 Follow(a) => apply(a),
130 Choice(a, b) => apply(a).or_else(|| apply(b)),
131 Sequence(a, b) => sequence(a, b),
132 Compound(a, b, c, d) => sequence(a, b).or_else(|| sequence(c, d)),
133 }
134}