Skip to main content

aoc/year2016/
day09.rs

1//! # Explosives in Cyberspace
2//!
3//! The only difference between part one and two is that we recursively decompress inner sequences.
4use crate::util::parse::*;
5
6pub fn parse(input: &str) -> &[u8] {
7    input.trim().as_bytes()
8}
9
10pub fn part1(input: &[u8]) -> usize {
11    decompress(input, false)
12}
13
14pub fn part2(input: &[u8]) -> usize {
15    decompress(input, true)
16}
17
18fn decompress(mut slice: &[u8], part_two: bool) -> usize {
19    let mut length = 0;
20
21    // Find the next marker.
22    while let Some(start) = slice.iter().position(|&b| b == b'(') {
23        let (next, amount) = number(&slice[start + 1..]);
24        let (next, repeat) = number(next);
25        let (data, rest) = next.split_at(amount);
26
27        // For part two, recursively decompress data.
28        let result = if part_two { decompress(data, true) } else { amount };
29
30        slice = rest;
31        length += start + result * repeat;
32    }
33
34    // Add remaining plain data that doesn't contain any marker.
35    length + slice.len()
36}
37
38fn number(slice: &[u8]) -> (&[u8], usize) {
39    let end = slice.iter().position(|b| !b.is_ascii_digit()).unwrap();
40    let n = slice[..end].iter().fold(0, |n, &b| 10 * n + b.to_decimal::<usize>());
41    // Skip over trailing delimiter.
42    (&slice[end + 1..], n)
43}