Esempio n. 1
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> grid = await ReadResourceAsLinesAsync();

        var slopes = new[]
        {
            new Point(1, 1),
            new Point(5, 1),
            new Point(7, 1),
            new Point(1, 2),
        };

        TreeCollisions = GetTreeCollisionCount(grid, 3, 1);

        long product = TreeCollisions;

        for (int i = 0; i < slopes.Length; i++)
        {
            var slope = slopes[i];
            product *= GetTreeCollisionCount(grid, slope.X, slope.Y);
        }

        ProductOfTreeCollisions = product;

        if (Verbose)
        {
            Logger.WriteLine("{0} trees would be encountered using a right-3/down-1 slope.", TreeCollisions);
            Logger.WriteLine("The product of the collisions from traversing the slopes is {0}.", ProductOfTreeCollisions);
        }

        return(PuzzleResult.Create(TreeCollisions, ProductOfTreeCollisions));
    }
Esempio n. 2
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        int    rows          = Parse <int>(args[0]);
        string firstRowTiles = args.Length > 1 ? args[1] : (await ReadResourceAsStringAsync()).TrimEnd();

        (int safeTileCount, string visualization) = FindSafeTileCount(firstRowTiles, rows, Logger);

        SafeTileCount = safeTileCount;

        if (Verbose)
        {
            Logger.WriteLine($"The number of safe tiles is {SafeTileCount:N0}.");
        }

        var result = new PuzzleResult();

        result.Solutions.Add(SafeTileCount);

        if (!string.IsNullOrEmpty(visualization))
        {
            result.Visualizations.Add(visualization);
        }

        return(result);
    }
Esempio n. 3
0
    public async Task Puzzle_Solve_Returns_Correct_Value_Based_On_Args_Length()
    {
        // Arrange
        string[] args = new[] { "1" };
        var      cancellationToken = CancellationToken.None;

        var target = new MyPuzzle(2)
        {
            Logger = Logger,
        };

        // Act and Assert
        await Assert.ThrowsAsync <PuzzleException>(() => target.SolveAsync(args, cancellationToken));

        // Arrange
        args   = Array.Empty <string>();
        target = new MyPuzzle(1);

        // Act and Assert
        await Assert.ThrowsAsync <PuzzleException>(() => target.SolveAsync(args, cancellationToken));

        // Arrange
        target = new MyPuzzle(0);

        // Act
        PuzzleResult actual = await target.SolveAsync(args, cancellationToken);

        // Assert
        actual.ShouldNotBeNull();
        actual.Solutions.ShouldNotBeNull();
        actual.Solutions.Count.ShouldBe(1);
        actual.Solutions[0].ShouldBe(42);
        target.Answer.ShouldBe(42);
    }
Esempio n. 4
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        var containerVolumes = await ReadResourceAsNumbersAsync <int>();

        int volume = Parse <int>(args[0]);

        var combinations = GetContainerCombinations(volume, containerVolumes);

        var combinationsWithLeastContainers = combinations
                                              .GroupBy((p) => p.Count)
                                              .OrderBy((p) => p.Key)
                                              .First();

        Combinations = combinations.Count;
        CombinationsWithMinimumContainers = combinationsWithLeastContainers.Count();

        if (Verbose)
        {
            Logger.WriteLine(
                "There are {0:N0} combinations of containers that can store {1:0} liters of eggnog.",
                Combinations,
                volume);

            Logger.WriteLine(
                "There are {0:N0} combinations of containers that can store {1:0} liters of eggnog using {2} containers.",
                CombinationsWithMinimumContainers,
                volume,
                combinationsWithLeastContainers.Key);
        }

        return(PuzzleResult.Create(Combinations, CombinationsWithMinimumContainers));
    }
Esempio n. 5
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        Stream resource = Resource ?? ReadResource();

        try
        {
            using var document = await JsonDocument.ParseAsync(resource, cancellationToken : cancellationToken);

            string keyToIgnore = args.Length > 0 ? args[0] : string.Empty;

            Sum = SumIntegerValues(document.RootElement, keyToIgnore);

            if (Verbose)
            {
                Logger.WriteLine("The sum of the integers in the JSON document is {0:N0}.", Sum);
            }
        }
        finally
        {
            if (Resource is null)
            {
                await resource.DisposeAsync();
            }
        }

        return(PuzzleResult.Create(Sum));
    }
Esempio n. 6
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string difficulty = args.Length == 1 ? args[0] : "easy";

        // Play the game 100,000 times with random choices of spells
        const int Iterations = 100000;

        var solutions = new List <(bool DidWizardWin, int ManaSpent)>(Iterations);

        while (solutions.Count < Iterations)
        {
            var result = Fight((wizard, spells) => spells.ElementAt(RandomNumberGenerator.GetInt32(0, spells.Count)), difficulty);
            solutions.Add(result);
        }

        MinimumCostToWin = solutions
                           .Where((p) => p.DidWizardWin)
                           .Min((p) => p.ManaSpent);

        if (Verbose)
        {
            Logger.WriteLine(
                "The minimum amount of mana that can be spent to win on {0} difficulty is {1:N0}.",
                difficulty,
                MinimumCostToWin);
        }

        return(PuzzleResult.Create(MinimumCostToWin));
    }
Esempio n. 7
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> layout = await ReadResourceAsLinesAsync();

        (int occupiedSeatsV1, string visualizationV1) = GetOccupiedSeats(layout, version: 1);
        (int occupiedSeatsV2, string visualizationV2) = GetOccupiedSeats(layout, version: 2);

        OccupiedSeatsV1 = occupiedSeatsV1;
        OccupiedSeatsV2 = occupiedSeatsV2;

        if (Verbose)
        {
            Logger.WriteLine("There are {0} occupied seats using the first set of rules.", OccupiedSeatsV1);
            Logger.WriteLine("There are {0} occupied seats using the second set of rules.", OccupiedSeatsV2);
        }

        var result = new PuzzleResult();

        result.Solutions.Add(OccupiedSeatsV1);
        result.Visualizations.Add(visualizationV1);

        result.Solutions.Add(OccupiedSeatsV2);
        result.Visualizations.Add(visualizationV2);

        return(result);
    }
Esempio n. 8
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        int timeIndex = Parse <int>(args[0], NumberStyles.Integer & ~NumberStyles.AllowLeadingSign);

        if (timeIndex < 0)
        {
            throw new PuzzleException("The time index specified is invalid.");
        }

        IList <string> flightData = await ReadResourceAsLinesAsync();

        MaximumReindeerDistance = GetMaximumDistanceOfFastestReindeer(flightData, timeIndex);

        if (Verbose)
        {
            Logger.WriteLine("After {0:N0} seconds, the furthest reindeer is {1:N0} km away.", timeIndex, MaximumReindeerDistance);
        }

        MaximumReindeerPoints = GetMaximumPointsOfFastestReindeer(flightData, timeIndex);

        if (Verbose)
        {
            Logger.WriteLine("After {0:N0} seconds, the reindeer in the lead has {1:N0} points.", timeIndex, MaximumReindeerPoints);
        }

        return(PuzzleResult.Create(MaximumReindeerDistance, MaximumReindeerPoints));
    }
Esempio n. 9
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string value      = args[0];
        int    iterations = Parse <int>(args[1], NumberStyles.Integer & ~NumberStyles.AllowLeadingSign);

        string result = value;

        for (int i = 0; i < iterations; i++)
        {
            result = AsLookAndSay(result);
        }

        Solution = result.Length;

        if (Verbose)
        {
            Logger.WriteLine(
                "The length of the result for input '{0}' after {1:N0} iterations is {2:N0}.",
                value,
                iterations,
                result.Length);
        }

        return(PuzzleResult.Create(Solution));
    }
        public void Puzzles(PuzzleResult expectedPuzzleResult)
        {
            var runner = new PuzzleRunner();

            var puzzleResult = runner.Run(expectedPuzzleResult.PuzzleName);

            Assert.Equal(expectedPuzzleResult.Part1.Result, puzzleResult.Part1.Result);
            if (expectedPuzzleResult.Part2 != null)
            {
                Assert.Equal(expectedPuzzleResult.Part2.Result, puzzleResult.Part2.Result);
            }
        }
Esempio n. 11
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string program = await ReadResourceAsStringAsync();

        Output = await RunProgramAsync(program, adjust : true, cancellationToken);

        if (Verbose)
        {
            Logger.WriteLine("The value at position 0 after the program halts is {0}.", Output[0]);
        }

        return(PuzzleResult.Create(Output[0]));
    }
Esempio n. 12
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string current = args[0];

        NextPassword = GenerateNextPassword(current);

        if (Verbose)
        {
            Logger.WriteLine("Santa's new password should be '{0}'.", NextPassword);
        }

        return(PuzzleResult.Create(NextPassword));
    }
Esempio n. 13
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string key = args[0];

        SquaresUsed = GetSquaresUsed(key);

        if (Verbose)
        {
            Logger.WriteLine($"The number of squares used for key {key} is {SquaresUsed:N0}.");
        }

        return(PuzzleResult.Create(SquaresUsed));
    }
Esempio n. 14
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        CountV1 = GetPasswordsInRange(args[0], rulesVersion: 1);
        CountV2 = GetPasswordsInRange(args[0], rulesVersion: 2);

        if (Verbose)
        {
            Logger.WriteLine("{0} different passwords within the range meet the criteria for version 1.", CountV1);
            Logger.WriteLine("{0} different passwords within the range meet the criteria for version 2.", CountV2);
        }

        return(PuzzleResult.Create(CountV1, CountV2));
    }
Esempio n. 15
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> game = await ReadResourceAsLinesAsync();

        (FirstWinningScore, LastWinningScore) = PlayBingo(game);

        if (Verbose)
        {
            Logger.WriteLine("The score of the first winning Bingo card is {0:N0}.", FirstWinningScore);
            Logger.WriteLine("The score of the last winning Bingo card is {0:N0}.", LastWinningScore);
        }

        return(PuzzleResult.Create(FirstWinningScore, LastWinningScore));
    }
Esempio n. 16
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> batch = await ReadResourceAsLinesAsync();

        (ValidPassports, VerifiedPassports) = VerifyPassports(batch);

        if (Verbose)
        {
            Logger.WriteLine("There are {0} valid passports.", ValidPassports);
            Logger.WriteLine("There are {0} verified passports.", VerifiedPassports);
        }

        return(PuzzleResult.Create(ValidPassports, VerifiedPassports));
    }
Esempio n. 17
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> output = await ReadResourceAsLinesAsync();

        (ViableNodePairs, MinimumStepsToExtract) = CountViableNodePairs(output, Logger);

        if (Verbose)
        {
            Logger.WriteLine("The number of viable pairs of nodes is {0:N0}.", ViableNodePairs);
            Logger.WriteLine("The fewest number of steps required to extract the goal data is {0:N0}.", MinimumStepsToExtract);
        }

        return(PuzzleResult.Create(ViableNodePairs, MinimumStepsToExtract));
    }
Esempio n. 18
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        long   input   = Parse <long>(args[0]);
        string program = await ReadResourceAsStringAsync();

        Keycode = (await RunProgramAsync(program, input, cancellationToken))[0];

        if (Verbose)
        {
            Logger.WriteLine("The program produces BOOST keycode {0}.", Keycode);
        }

        return(PuzzleResult.Create(Keycode));
    }
Esempio n. 19
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string stream = (await ReadResourceAsStringAsync()).Trim();

        (TotalScore, GarbageCount) = ParseStream(stream);

        if (Verbose)
        {
            Logger.WriteLine($"The total score for all the groups is {TotalScore:N0}.");
            Logger.WriteLine($"There are {GarbageCount:N0} non-canceled characters within the garbage.");
        }

        return(PuzzleResult.Create(TotalScore, GarbageCount));
    }
Esempio n. 20
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> lines = await ReadResourceAsLinesAsync();

        (SyntaxErrorScore, MiddleAutoCompleteScore) = Compile(lines);

        if (Verbose)
        {
            Logger.WriteLine("The total syntax error score is {0:N0}.", SyntaxErrorScore);
            Logger.WriteLine("The middle auto-complete score is {0:N0}.", MiddleAutoCompleteScore);
        }

        return(PuzzleResult.Create(SyntaxErrorScore, MiddleAutoCompleteScore));
    }
Esempio n. 21
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string value = await ReadResourceAsStringAsync();

        (FinalFloor, FirstBasementInstruction) = GetFinalFloorAndFirstInstructionBasementReached(value);

        if (Verbose)
        {
            Logger.WriteLine("Santa should go to floor {0}.", FinalFloor);
            Logger.WriteLine("Santa first enters the basement after following instruction {0:N0}.", FirstBasementInstruction);
        }

        return(PuzzleResult.Create(FinalFloor, FirstBasementInstruction));
    }
Esempio n. 22
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string initial = args[0];
        int    size    = Parse <int>(args[1]);

        Checksum = GetDiskChecksum(initial, size);

        if (Verbose)
        {
            Logger.WriteLine($"The checksum for the generated disk data is '{Checksum}'.");
        }

        return(PuzzleResult.Create(Checksum));
    }
Esempio n. 23
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> numbers = await ReadResourceAsLinesAsync();

        (MagnitudeOfSum, LargestSumMagnitude) = Sum(numbers);

        if (Verbose)
        {
            Logger.WriteLine("The magnitude of the final sum is {0:N0}.", MagnitudeOfSum);
            Logger.WriteLine("The largest magnitude of any sum of two numbers is {0:N0}.", LargestSumMagnitude);
        }

        return(PuzzleResult.Create(MagnitudeOfSum, LargestSumMagnitude));
    }
Esempio n. 24
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> log = await ReadResourceAsLinesAsync();

        (SleepiestGuardMinute, SleepiestMinuteGuard) = GetSleepiestGuardsMinutes(log);

        if (Verbose)
        {
            Logger.WriteLine($"The ID of the sleepiest guard multiplied by the most common minute is {SleepiestGuardMinute:N0}.");
            Logger.WriteLine($"The most common minute a guard was asleep in multiplied by the guard's ID is {SleepiestMinuteGuard:N0}.");
        }

        return(PuzzleResult.Create(SleepiestGuardMinute, SleepiestMinuteGuard));
    }
Esempio n. 25
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <int> sequence = await ReadResourceAsNumbersAsync <int>();

        (Frequency, FirstRepeatedFrequency) = CalculateFrequencyWithRepetition(sequence);

        if (Verbose)
        {
            Logger.WriteLine($"The resulting frequency is {Frequency:N0}.");
            Logger.WriteLine($"The first repeated frequency is {FirstRepeatedFrequency:N0}.");
        }

        return(PuzzleResult.Create(Frequency, FirstRepeatedFrequency));
    }
Esempio n. 26
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        int count   = Parse <int>(args[0]);
        int version = args.Length > 1 ? Parse <int>(args[1]) : 1;

        ElfWithAllPresents = FindElfThatGetsAllPresents(count, version);

        if (Verbose)
        {
            Logger.WriteLine($"The elf that gets all the presents using version {version} of the rules is {ElfWithAllPresents:N0}.");
        }

        return(PuzzleResult.Create(ElfWithAllPresents));
    }
Esempio n. 27
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        int favoriteNumber = Parse <int>(args[0]);

        FewestStepsToReach31X39Y = GetMinimumStepsToReachCoordinate(favoriteNumber, 31, 39);
        LocationsWithin50        = CountLocationsWithin50Steps(favoriteNumber);

        if (Verbose)
        {
            Logger.WriteLine("The fewest number of steps required to reach 31,39 is {0}.", FewestStepsToReach31X39Y);
            Logger.WriteLine("The number of locations within 50 steps of the origin is {0}.", LocationsWithin50);
        }

        return(PuzzleResult.Create(FewestStepsToReach31X39Y, LocationsWithin50));
    }
Esempio n. 28
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> values = await ReadResourceAsLinesAsync();

        ValidPasswordsV1 = GetValidPasswordCount(values, policyVersion: 1);
        ValidPasswordsV2 = GetValidPasswordCount(values, policyVersion: 2);

        if (Verbose)
        {
            Logger.WriteLine("There are {0} valid passwords using policy version 1.", ValidPasswordsV1);
            Logger.WriteLine("There are {0} valid passwords using policy version 2.", ValidPasswordsV2);
        }

        return(PuzzleResult.Create(ValidPasswordsV1, ValidPasswordsV2));
    }
Esempio n. 29
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <int> fish = (await ReadResourceAsStringAsync()).AsNumbers <int>().ToArray();

        FishCount80  = CountFish(fish, days: 80);
        FishCount256 = CountFish(fish, days: 256);

        if (Verbose)
        {
            Logger.WriteLine("There are {0:N0} lanternfish after 80 days.", FishCount80);
            Logger.WriteLine("There are {0:N0} lanternfish after 256 days.", FishCount256);
        }

        return(PuzzleResult.Create(FishCount80, FishCount256));
    }
Esempio n. 30
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <string> structure = await ReadResourceAsLinesAsync();

        BottomProgramName             = FindBottomProgramName(structure);
        DesiredWeightOfUnbalancedDisc = FindDesiredWeightOfUnbalancedDisc(structure);

        if (Verbose)
        {
            Logger.WriteLine($"The name of the bottom program is '{BottomProgramName}'.");
            Logger.WriteLine($"The desired weight of the program to balance the structure is {DesiredWeightOfUnbalancedDisc:N0}.");
        }

        return(PuzzleResult.Create(BottomProgramName, DesiredWeightOfUnbalancedDisc));
    }