01020304

Advent of Code

2026/4

Perilous Pier

in C#

by encse

The ever-growing train slowly rolls to a stop near an array of shipping containers at the top secret North Pole port. Although these containers surely hold many useful things, the Elves are specifically looking for a shipment of parabolas.

The shipping containers are normally well-organized, but things have fallen into mild disarray due to the recent weather. Even the barcodes on the shipping containers have been too damaged to read clearly!

Visit the website for the full story and full puzzle description.

namespace AdventOfCode.Y2026.Day04;

using System.Linq;
using System.Reflection.Metadata;

[ProblemName("Perilous Pier")]
class Solution : Solver {

    public object PartOne(string input) => input.Split('\n').Sum(Solve);

    public object PartTwo(string input) => Solve(input.Replace("\n", ""));

    int Solve(string barcode) =>
        Enumerable
            .Range(1, barcode.Length)
            .First(instrCount => TryProgram(barcode, instrCount));

    bool TryProgram(string input, int instrCount) {
        // set each instruction to '?' at the beginning
        var prog = new string('?', instrCount).ToArray();

        for (var i = 0; i < input.Length; i++) {
            var inputChar = input[i];
            var progChar = prog[i % instrCount];

            if (inputChar == '?') {
                continue;
            }

            // The first non '?' occurrence in the input creates a requirement
            // in the program for the later iterations. Compare otherwise.
            if (progChar == '?') {
                prog[i % instrCount] = inputChar;
            } else if (progChar != inputChar) {
                return false;
            }
        }
        return true;
    }
}

Please ☆ my repo if you like it!

© 2026 | Advent of Code is a registered trademark in the US | Images provided by Bing and Nano Banana