01020304050607080910111213141516171819202122232425

Advent of Code

2019/4

Secure Container

in C#

by encse

You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out.

However, they do remember a few key facts about the password:

Read the full puzzle.

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace AdventOfCode.Y2019.Day04;

[ProblemName("Secure Container")]
class Solution : Solver {

    public object PartOne(string input) => Solve(input, true);
    public object PartTwo(string input) => Solve(input, false);
    private int Solve(string input, bool trippletsAllowed) {

        var args = input.Split("-").Select(int.Parse).ToArray();
        return (
            from i in Enumerable.Range(args[0], args[1] - args[0] + 1)
            where OK(i.ToString(), trippletsAllowed)
            select i
        ).Count();
    }

    private bool OK(string password, bool trippletsAllowed) {

        if (string.Join("", password.OrderBy(ch => ch)) != password) {
            return false;
        }

        return (
            from sequence in Split(password)
            where sequence.Length >= 2 && (trippletsAllowed || sequence.Length == 2)
            select sequence
        ).Any();
    }

    private IEnumerable<string> Split(string st) {
        var ich = 0;
        while (ich < st.Length) {
            var sequence = Regex.Match(st.Substring(ich), @$"[{st[ich]}]+").Value;
            yield return sequence;
            ich += sequence.Length;
        }
    }
}

Please ☆ my repo if you like it!

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