01020304050607080910111213141516171819202122232425

Advent of Code

2016/9

Explosives in Cyberspace

in C#

by encse

Wandering around a secure area, you come across a datalink port to a new part of the network. After briefly scanning it for interesting files, you find one file in particular that catches your attention. It's compressed with an experimental format, but fortunately, the documentation for the format is nearby.

The format compresses a sequence of characters. Whitespace is ignored. To indicate that some sequence should be repeated, a marker is added to the file, like (10x2). To decompress this marker, take the subsequent 10 characters and repeat them 2 times. Then, continue reading the file after the repeated data. The marker itself is not included in the decompressed output.

Read the full puzzle.

using System.Text.RegularExpressions;

namespace AdventOfCode.Y2016.Day09;

[ProblemName("Explosives in Cyberspace")]
class Solution : Solver {

    public object PartOne(string input) {
        return Expand(input, 0, input.Length, false);
    }

    public object PartTwo(string input) {
        return Expand(input, 0, input.Length, true);
    }

    long Expand(string input, int i, int lim, bool recursive) {
        var res = 0L;
        while (i < lim) {
            if (input[i] == '(') {
                var j = input.IndexOf(')', i + 1);
                var m = Regex.Match(input.Substring(i + 1, j - i - 1), @"(\d+)x(\d+)");
                var length = int.Parse(m.Groups[1].Value);
                var mul = int.Parse(m.Groups[2].Value);
                res += recursive ? Expand(input, j + 1, j + length + 1, recursive) * mul : length * mul;
                i = j + length + 1;
            } else {
                res++;
                i++;
            }
        }
        return res;
    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator