Пример #1
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));
    }
Пример #2
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));
    }
Пример #3
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));
    }
Пример #4
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));
    }
Пример #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));
    }
Пример #6
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));
    }
Пример #7
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));
    }
Пример #8
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));
    }
Пример #9
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]));
    }
Пример #10
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));
    }
Пример #11
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));
    }
Пример #12
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));
    }
Пример #13
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));
    }
Пример #14
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));
    }
Пример #15
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));
    }
Пример #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));
    }
Пример #17
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));
    }
Пример #18
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));
    }
Пример #19
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));
    }
Пример #20
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));
    }
Пример #21
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));
    }
Пример #22
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));
    }
Пример #23
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));
    }
Пример #24
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string digits = (await ReadResourceAsStringAsync()).TrimEnd();

        CaptchaSolutionNext     = CalculateSum(digits, useOppositeDigit: false);
        CaptchaSolutionOpposite = CalculateSum(digits, useOppositeDigit: true);

        if (Verbose)
        {
            Logger.WriteLine($"The solution to the first captcha is {CaptchaSolutionNext:N0}.");
            Logger.WriteLine($"The solution to the second captcha is {CaptchaSolutionOpposite:N0}.");
        }

        return(PuzzleResult.Create(CaptchaSolutionNext, CaptchaSolutionOpposite));
    }
Пример #25
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));
    }
Пример #26
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        IList <int> masses = await ReadResourceAsNumbersAsync <int>();

        TotalFuelRequiredForModules = GetFuelRequirementsForMasses(masses);
        TotalFuelRequiredForRocket  = GetFuelRequirementsForRocket(masses);

        if (Verbose)
        {
            Logger.WriteLine("{0} fuel is required for the modules.", TotalFuelRequiredForModules);
            Logger.WriteLine("{0} fuel is required for the fully-fuelled rocket.", TotalFuelRequiredForRocket);
        }

        return(PuzzleResult.Create(TotalFuelRequiredForModules, TotalFuelRequiredForRocket));
    }
Пример #27
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));
    }
Пример #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));
    }
Пример #29
0
    /// <inheritdoc />
    protected override Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        string doorId = args[0];

        Password = GeneratePassword(doorId, isPositionSpecifiedByHash: false);
        PasswordWhenPositionIsIndicated = GeneratePassword(doorId, isPositionSpecifiedByHash: true);

        if (Verbose)
        {
            Logger.WriteLine($"The password for door '{doorId}' is '{Password}'.");
            Logger.WriteLine($"The password for door '{doorId}' is '{PasswordWhenPositionIsIndicated}' when the position is specified in the hash.");
        }

        return(PuzzleResult.Create(Password, PasswordWhenPositionIsIndicated));
    }
Пример #30
0
    /// <inheritdoc />
    protected override async Task <PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
    {
        ICollection <string> passphrases = await ReadResourceAsLinesAsync();

        ValidPassphraseCountV1 = passphrases.Count((p) => IsPassphraseValid(p, 1));
        ValidPassphraseCountV2 = passphrases.Count((p) => IsPassphraseValid(p, 2));

        if (Verbose)
        {
            Logger.WriteLine($"There are {ValidPassphraseCountV1:N0} valid passphrases using version 1 of the policy.");
            Logger.WriteLine($"There are {ValidPassphraseCountV2:N0} valid passphrases using version 2 of the policy.");
        }

        return(PuzzleResult.Create(ValidPassphraseCountV1, ValidPassphraseCountV2));
    }