Skip to main content

aoc/year2021/
day16.rs

1//! # Packet Decoder
2//!
3//! [`BitStream`] is the key to making this problem tractable. It works like an iterator, allowing
4//! us to consume an arbitrary number of bits from the input and convert this to a number.
5//!
6//! It works by maintaining an internal `u64` buffer. If the requested number of bits is larger than
7//! the buffer's current size then additional bits are added to the buffer 4 at a time from each
8//! hexadecimal digit of the input data.
9//!
10//! Additionally, it keeps track of the total number of bits consumed so far. This is needed when
11//! parsing packets that use the total length in bits to determine sub-packets.
12//!
13//! The decoded packet data is stored as a tree-like struct allowing recursive solutions to part one
14//! and part two to reuse the same decoded input.
15use std::iter::from_fn;
16use std::str::Bytes;
17
18struct BitStream<'a> {
19    available: u64,
20    bits: u64,
21    read: u64,
22    iter: Bytes<'a>,
23}
24
25impl BitStream<'_> {
26    fn new(s: &str) -> BitStream<'_> {
27        BitStream { available: 0, bits: 0, read: 0, iter: s.bytes() }
28    }
29
30    fn next(&mut self, amount: u64) -> u64 {
31        while self.available < amount {
32            let b = self.iter.next().unwrap();
33            let digit = char::from(b).to_digit(16).unwrap();
34
35            self.available += 4;
36            self.bits = (self.bits << 4) | u64::from(digit);
37        }
38
39        self.available -= amount;
40        self.read += amount;
41
42        let mask = (1 << amount) - 1;
43        (self.bits >> self.available) & mask
44    }
45}
46
47pub enum Packet {
48    Literal { version: u64, value: u64 },
49    Operator { version: u64, type_id: u64, packets: Vec<Self> },
50}
51
52impl Packet {
53    fn new(bit_stream: &mut BitStream<'_>) -> Self {
54        let version = bit_stream.next(3);
55        let type_id = bit_stream.next(3);
56
57        if type_id == 4 {
58            let mut todo = true;
59            let mut value = 0;
60
61            while todo {
62                todo = bit_stream.next(1) == 1;
63                value = (value << 4) | bit_stream.next(4);
64            }
65
66            Self::Literal { version, value }
67        } else {
68            let packets = if bit_stream.next(1) == 0 {
69                let target = bit_stream.next(15) + bit_stream.read;
70                from_fn(|| (bit_stream.read < target).then(|| Self::new(bit_stream))).collect()
71            } else {
72                let sub_packets = bit_stream.next(11) as usize;
73                Vec::from_fn(sub_packets, |_| Self::new(bit_stream))
74            };
75
76            Self::Operator { version, type_id, packets }
77        }
78    }
79}
80
81pub fn parse(input: &str) -> Packet {
82    Packet::new(&mut BitStream::new(input))
83}
84
85pub fn part1(packet: &Packet) -> u64 {
86    match packet {
87        Packet::Literal { version, .. } => *version,
88        Packet::Operator { version, packets, .. } => {
89            *version + packets.iter().map(part1).sum::<u64>()
90        }
91    }
92}
93
94pub fn part2(packet: &Packet) -> u64 {
95    match packet {
96        Packet::Literal { value, .. } => *value,
97        Packet::Operator { type_id, packets, .. } => {
98            let mut iter = packets.iter().map(part2);
99            match type_id {
100                0 => iter.sum(),
101                1 => iter.product(),
102                2 => iter.min().unwrap(),
103                3 => iter.max().unwrap(),
104                5 => u64::from(iter.next().unwrap() > iter.next().unwrap()),
105                6 => u64::from(iter.next().unwrap() < iter.next().unwrap()),
106                7 => u64::from(iter.next().unwrap() == iter.next().unwrap()),
107                _ => unreachable!(),
108            }
109        }
110    }
111}