aoc/year2022/day13.rs
1//! # Distress Signal
2//!
3//! One possible approach is to parse the input into a tree, then compare recursively node
4//! by node. We're going to use a much faster and simpler approach by noting an observation about
5//! the input data. If the sequence `10` is replaced by any single character greater than `9` then
6//! we can compare the 2 packets *lexicographically*. We'll replace all occurrences of `10` with `A`
7//! then compare packets character by character.
8//!
9//! The rules to compare 2 packets become:
10//! * If both characters are the same then it's a draw, move onto the next character in each packet.
11//! * If the first packet is `]` and the second packet is anything else, then the first list is
12//! shorter so the packets are in order.
13//! * Conversely, if the second packet is `]` and the first packet is anything else, the packets are
14//! not in order.
15//! * If the first packet is an opening `[` and the second character is anything else, then we're
16//! comparing a number with a list, so *push* the second character back onto the list to check
17//! again along with a closing `]` character.
18//! * Do a similar push if the second character is an opening `[` and the first is anything else.
19//! * Finally, compare the 2 characters by value. Since we've already covered the equal case, one is
20//! guaranteed to be greater than or less than the other.
21use crate::util::iter::*;
22
23struct Packet<'a> {
24 slice: &'a [u8],
25 extra: Vec<u8>,
26}
27
28impl Packet<'_> {
29 fn new(str: &str) -> Packet<'_> {
30 Packet { slice: str.as_bytes(), extra: Vec::new() }
31 }
32}
33
34impl Iterator for Packet<'_> {
35 type Item = u8;
36
37 fn next(&mut self) -> Option<Self::Item> {
38 self.extra.pop().or_else(|| {
39 // Replace occurrences of "10" with "A".
40 let (next, rest) = match self.slice {
41 [b'1', b'0', rest @ ..] => (b'A', rest),
42 [next, rest @ ..] => (*next, rest),
43 [] => return None,
44 };
45 self.slice = rest;
46 Some(next)
47 })
48 }
49}
50
51pub fn parse(input: &str) -> Vec<&str> {
52 input.lines().filter(|line| !line.is_empty()).collect()
53}
54
55/// Count adjacent pairs of packets that are in order.
56pub fn part1(input: &[&str]) -> usize {
57 input
58 .iter()
59 .chunk::<2>()
60 .enumerate()
61 .filter_map(|(i, [a, b])| compare(a, b).then_some(i + 1))
62 .sum()
63}
64
65/// Find the position of `[[2]]` and `[[6]]` in linear `O(n)` time.
66///
67/// One approach would be to insert `[[2]]` and `[[6]]` into the list, sort in `O(nlogn)` time,
68/// then find the indices of the 2 values in `O(n)` time.
69///
70/// A much faster approach is to iterate over the list, comparing each packet first with `[[2]]`.
71/// If the packets are in order, then increment the positions of *both* `[[2]]` and `[[6]]`,
72/// since `[[2]]` is less than `[[6]]`.
73///
74/// If the packet and `[[2]]` are not in order, then also check against `[[6]]`, incrementing only
75/// the second index if the 2 packets are in order.
76///
77/// This obtains the relative indices of `[[2]]` and `[[6]]` efficiently in fewer than `2n`
78/// comparisons.
79pub fn part2(input: &[&str]) -> u32 {
80 let mut first = 1;
81 let mut second = 2;
82
83 for packet in input {
84 if compare(packet, "[[2]]") {
85 first += 1;
86 second += 1;
87 } else if compare(packet, "[[6]]") {
88 second += 1;
89 }
90 }
91
92 first * second
93}
94
95/// Compare 2 packets using the rules listed in the module description.
96///
97/// It's faster to use 2 temporary `vec`s to store extra characters, rather than copy each
98/// packet into a mutable [`VecDeque`]. We use the [`or_else`] method on [`Option`] to check
99/// in the temporary `vec` for available characters first.
100///
101/// [`VecDeque`]: std::collections::VecDeque
102/// [`or_else`]: Option::or_else
103fn compare(left: &str, right: &str) -> bool {
104 let mut left = Packet::new(left);
105 let mut right = Packet::new(right);
106
107 while let (Some(a), Some(b)) = (left.next(), right.next()) {
108 match (a, b) {
109 (a, b) if a == b => (),
110 (b']', _) => return true,
111 (_, b']') => return false,
112 (b'[', b) => {
113 right.extra.push(b']');
114 right.extra.push(b);
115 }
116 (a, b'[') => {
117 left.extra.push(b']');
118 left.extra.push(a);
119 }
120 (a, b) => return a < b,
121 }
122 }
123
124 unreachable!()
125}