Example #1
0
        public int getTrees(int xStep, int yStep)
        {
            string[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3));
            int      width     = inputsRaw[0].Length;

            int currX = 0;
            int currY = 0;

            int countTree = 0;

            while (currY < inputsRaw.Length - 1)
            {
                currX += xStep;
                currY += yStep;

                if (currX > width - 1)
                {
                    currX = currX % width;
                }

                if (inputsRaw[currY][currX] == '#')
                {
                    countTree++;
                }
            }

            return(countTree);
        }
Example #2
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        int part1 = 0;
        int part2 = 0;

        foreach ((int min, int max, char target, string password) in this.Data)
        {
            //Part 1
            int occurrences = password.Count(c => c == target);
            if (occurrences >= min && occurrences <= max)
            {
                part1++;
            }

            //Part 2
            if (password[min - 1] == target)
            {
                if (password[max - 1] != target)
                {
                    part2++;
                }
            }
            else if (password[max - 1] == target)
            {
                part2++;
            }
        }

        AoCUtils.LogPart1(part1);
        AoCUtils.LogPart2(part2);
    }
Example #3
0
        public string SolveP2()
        {
            int target = 2020;

            List <string> inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).ToList();
            List <int>    inputs    = inputsRaw.Select(x => Int32.Parse(x)).Where(x => x < target).ToList();

            for (int ii = 0; ii < inputs.Count; ii++)
            {
                for (int jj = 0; jj < inputs.Count; jj++)
                {
                    for (int kk = 0; kk < inputs.Count; kk++)
                    {
                        if (ii == jj || ii == kk || jj == kk)
                        {
                            continue;
                        }

                        if (inputs[ii] + inputs[jj] + inputs[kk] == target)
                        {
                            return((inputs[ii] * inputs[jj] * inputs[kk]).ToString());
                        }
                    }
                }
            }

            return(null);
        }
Example #4
0
        public string SolveP3()
        {
            int target = 3232322;

            List <string> inputsRaw = AoCUtils.readInputFile("01_3").ToList();
            List <int>    inputs    = inputsRaw.Select(x => Int32.Parse(x)).Where(x => x < target).ToList();

            for (int ii = 0; ii < inputs.Count; ii++)
            {
                for (int jj = 0; jj < inputs.Count; jj++)
                {
                    for (int kk = 0; kk < inputs.Count; kk++)
                    {
                        if (ii == jj || ii == kk || jj == kk)
                        {
                            continue;
                        }

                        if (inputs[ii] + inputs[jj] + inputs[kk] == target)
                        {
                            long temp1      = inputs[ii];
                            long temp2      = inputs[jj];
                            long temp3      = inputs[kk];
                            long prodResult = temp1 * temp2 * temp3;
                            return(prodResult.ToString());
                        }
                    }
                }
            }

            return(null);
        }
Example #5
0
        public string SolveP2()
        {
            int count = 0;

            List <string> inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).ToList();

            foreach (string currPair in inputsRaw)
            {
                string[] components = currPair.Split(' ');

                string[] passLengths = components[0].Split('-');
                int      min         = Int32.Parse(passLengths[0]);
                int      max         = Int32.Parse(passLengths[1]);

                char reqChar = components[1].ToCharArray().First();

                char[]      password   = components[2].ToCharArray();
                List <char> charsAtInd = new List <char>()
                {
                    password[min - 1], password[max - 1]
                };
                int charCount = charsAtInd.Where(x => x == reqChar).Count();

                if (charCount == 1)
                {
                    count++;
                }
            }

            return(count.ToString());
        }
Example #6
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        // Search for best path to the end
        Vector2 <int> start = Vector2 <int> .Zero, end = (this.Grid.Width - 1, this.Grid.Height - 1);

        // ReSharper disable once AccessToModifiedClosure
        Vector2 <int>[] path  = SearchUtils.Search(start, end, p => Vector2 <int> .ManhattanDistance(p, end), node => FindNeighbours(node, this.Grid), MinSearchComparer.Comparer) !;
        int             total = path.Sum(p => this.Grid[p]);

        AoCUtils.LogPart1(total);

        // Create scaled map
        Grid <byte> fullMap = new(this.Data.Width * FULL_SIZE, this.Data.Height * FULL_SIZE);

        foreach (Vector2 <int> position in Vector2 <int> .Enumerate(this.Data.Width, this.Data.Height))
        {
            int risk = this.Data[position];
            foreach (Vector2 <int> offset in Vector2 <int> .Enumerate(FULL_SIZE, FULL_SIZE))
            {
                Vector2 <int> pos     = position + offset.Scale(this.Data.Width, this.Data.Height);
                int           newRisk = risk + offset.X + offset.Y;
                fullMap[pos] = (byte)(newRisk > 9 ? newRisk - 9 : newRisk);
            }
        }

        // Search for new best path
        end   = (fullMap.Width - 1, fullMap.Height - 1);
        path  = SearchUtils.Search(start, end, p => Vector2 <int> .ManhattanDistance(p, end), node => FindNeighbours(node, fullMap), MinSearchComparer.Comparer) !;
        total = path.Sum(p => fullMap[p]);
        AoCUtils.LogPart2(total);
    }
Example #7
0
        public string SolveP2()
        {
            string[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3));

            List <int> seatIds = new List <int>();

            int maxRow = 127;
            int maxCol = 7;

            foreach (string currLine in inputsRaw)
            {
                double rowStart = 0;
                double rowEnd   = maxRow;
                for (int ii = 0; ii < 7; ii++)
                {
                    if (currLine[ii] == 'F')
                    {
                        rowEnd = rowEnd - Math.Ceiling((rowEnd - rowStart) / 2);
                    }
                    else
                    {
                        rowStart = rowStart + Math.Ceiling((rowEnd - rowStart) / 2);
                    }
                }

                double colStart = 0;
                double colEnd   = maxCol;
                for (int ii = 7; ii < currLine.Length; ii++)
                {
                    if (currLine[ii] == 'L')
                    {
                        colEnd = colEnd - Math.Ceiling((colEnd - colStart) / 2);
                    }
                    else
                    {
                        colStart = colStart + Math.Ceiling((colEnd - colStart) / 2);
                    }
                }

                seatIds.Add((int)(rowStart * 8 + colStart));
            }

            int theSeat = 0;

            seatIds.Sort();
            for (int ii = 0; ii < seatIds.Count() - 1; ii++)
            {
                if (seatIds[ii + 1] - seatIds[ii] != 1)
                {
                    theSeat = seatIds[ii] + 1;
                }
            }

            return(theSeat.ToString());
        }
Example #8
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        this.VM.AddInput(1L);
        this.VM.Run();
        AoCUtils.LogPart1(this.VM.GetNextOutput());

        this.VM.Reset();
        this.VM.AddInput(2L);
        this.VM.Run();
        AoCUtils.LogPart2(this.VM.GetNextOutput());
    }
Example #9
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        this.VM.AddInput(1L);
        this.VM.Run();
        AoCUtils.LogPart1(string.Join(' ', this.Data.GetOutput()));

        this.VM.Reset();
        this.VM.AddInput(5L);
        this.VM.Run();
        AoCUtils.LogPart2(this.Data.GetNextOutput());
    }
Example #10
0
        public string SolveP3()
        {
            List <char> resultChar = new List <char>();

            List <string> inputsRaw = AoCUtils.readInputFile("02_3").ToList();

            foreach (string currPair in inputsRaw)
            {
                string[] components = currPair.Split(' ');

                string[] passLengths = components[0].Split('-');
                int      startInd    = Int32.Parse(passLengths[0]) - 1;
                int      endInd      = Int32.Parse(passLengths[1]) - 1;

                char reqChar = components[1].ToCharArray().First();

                string passwordFrag = components[2].Substring(startInd, endInd - startInd + 1);

                Boolean isPalindrone = true;
                for (int ii = 0; ii < passwordFrag.Length / 2; ii++)
                {
                    if (passwordFrag[ii] != passwordFrag[passwordFrag.Length - 1 - ii])
                    {
                        isPalindrone = false;
                    }
                }

                // A = 65 : Z = 90
                // a = 97 : z = 122
                if (isPalindrone)
                {
                    char rot13Char;
                    int  tempCode = (int)reqChar + 13;
                    if (reqChar <= 122 && reqChar >= 97 && tempCode > 122)
                    {
                        int offset = tempCode - 122;
                        rot13Char = (char)(97 + offset - 1);
                    }
                    else if (reqChar <= 90 && reqChar >= 65 && tempCode > 90)
                    {
                        int offset = tempCode - 90;
                        rot13Char = (char)(65 + offset - 1);
                    }
                    else
                    {
                        rot13Char = (char)tempCode;
                    }

                    resultChar.Add(rot13Char);
                }
            }

            return(new string(resultChar.ToArray()));
        }
Example #11
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        //Get all existing ingredients and allergens
        Dictionary <string, int> ingredientCount = new();
        HashSet <string>         allergens       = new();

        foreach (IngredientList list in this.Data)
        {
            //Loop through list ingredients
            foreach (string ingredient in list.Ingredients)
            {
                //Keep track of how many times we've seen the ingredient
                ingredientCount.TryGetValue(ingredient, out int amount);
                ingredientCount[ingredient] = amount + 1;
            }

            //Add all children allergens
            allergens.UnionWith(list.Allergens);
        }

        //Get impossible ingredients
        HashSet <string> impossible = new(ingredientCount.Keys);
        Dictionary <string, HashSet <string> > possibilities = new();

        foreach (string allergen in allergens)
        {
            //Remove all ingredients not present every time
            HashSet <string> ingredients = new(ingredientCount.Keys);
            foreach (IngredientList list in this.Data.Where(l => l.Allergens.Contains(allergen)))
            {
                ingredients.IntersectWith(list.Ingredients);
            }
            //Remove possible ingredients from impossible list
            impossible.ExceptWith(ingredients);
            possibilities.Add(allergen, ingredients);
        }
        AoCUtils.LogPart1(impossible.Sum(i => ingredientCount[i]));

        //Get definitive allergens
        SortedDictionary <string, string> sortedAllergens = new();

        while (!possibilities.IsEmpty())
        {
            //Get first known allergen
            (string allergen, HashSet <string> ingredients) = possibilities.First(p => p.Value.Count is 1);
            possibilities.Remove(allergen);
            string ingredient = ingredients.First();
            //Add to final sorted list and remove from other lists
            sortedAllergens.Add(allergen, ingredient);
            possibilities.ForEach(p => p.Value.Remove(ingredient));
        }
        AoCUtils.LogPart2(string.Join(',', sortedAllergens.Values));
    }
Example #12
0
        public string SolveP1()
        {
            string[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3));

            char shipDir = 'E';

            int[] currCoords = new int[2] {
                0, 0
            };

            foreach (string currInstr in inputsRaw)
            {
                char instr = currInstr[0];
                int  value = Int32.Parse(currInstr.Substring(1));

                int turns, ind;
                switch (instr)
                {
                case 'N':
                case 'E':
                case 'S':
                case 'W':
                    currCoords[0] += value * dirVectors[instr].Item1;
                    currCoords[1] += value * dirVectors[instr].Item2;
                    break;

                case 'F':
                    currCoords[0] += value * dirVectors[shipDir].Item1;
                    currCoords[1] += value * dirVectors[shipDir].Item2;
                    break;

                case 'R':
                    turns   = value / 90;
                    ind     = directions.IndexOf(shipDir);
                    ind    += turns;
                    ind    %= 4;
                    shipDir = directions[ind];
                    break;

                case 'L':
                    turns   = value / 90;
                    ind     = revDirections.IndexOf(shipDir);
                    ind    += turns;
                    ind    %= 4;
                    shipDir = revDirections[ind];
                    break;
                }
            }

            int result = Math.Abs(currCoords[0]) + Math.Abs(currCoords[1]);

            return(result.ToString());
        }
Example #13
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        // Get maximum crab value
        int max = this.Data.Max();
        // Minimize distance to any point within the crabs
        long best = (..^ max).AsEnumerable().Min(position => this.Data.Sum(crab => Math.Abs(position - crab)));

        AoCUtils.LogPart1(best);

        // Minimize the distance of triangular value
        best = (..^ max).AsEnumerable().Min(position => this.Data.Sum(crab => Math.Abs(position - crab).Triangular()));
        AoCUtils.LogPart2(best);
    }
Example #14
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        int risk = 0;
        List <Vector2 <int> > lowPoints = new();

        foreach (Vector2 <int> position in Vector2 <int> .Enumerate(this.Grid.Width, this.Grid.Height))
        {
            // Check if the position is a low point
            byte value = this.Grid[position];
            if (position.Adjacent()
                .Where(this.Grid.WithinGrid)
                .Any(pos => value >= this.Grid[pos]))
            {
                continue;
            }

            lowPoints.Add(position);
            risk += value + 1;
        }

        AoCUtils.LogPart1(risk);

        Queue <Vector2 <int> >   search = new();
        HashSet <Vector2 <int> > basin  = new();
        PriorityQueue <int>      sizes  = new(DescendingComparer <int> .Comparer);

        // Start from all low points
        foreach (Vector2 <int> lowPoint in lowPoints)
        {
            // Fill out basin
            search.Enqueue(lowPoint);
            basin.Add(search.Peek());
            while (search.TryDequeue(out Vector2 <int> current))
            {
                // Add adjacent not already searched
                current.Adjacent()
                .Where(pos => this.Grid.WithinGrid(pos) && this.Grid[pos] is not 9 && basin.Add(pos))
                .ForEach(search.Enqueue);
            }

            // Add basin size to sizes
            sizes.Enqueue(basin.Count);
            basin.Clear();
        }

        // Get three largest sizes
        int final = sizes.Dequeue() * sizes.Dequeue() * sizes.Dequeue();

        AoCUtils.LogPart2(final);
    }
Example #15
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        //Part one
        long result = CheckSlope((3, 1));

        AoCUtils.LogPart1(result);

        //Part two
        result *= CheckSlope((1, 1));
        result *= CheckSlope((5, 1));
        result *= CheckSlope((7, 1));
        result *= CheckSlope((1, 2));
        AoCUtils.LogPart2(result);
    }
Example #16
0
        public string SolveP2()
        {
            long[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).ToList().Select(x => long.Parse(x)).ToArray();

            // Invalid number from previous part
            long invalidNum = inputsRaw[539];

            Boolean     foundWeakness = false;
            long        runningSum    = 0;
            long        runningCount  = 0;
            int         lastId        = 0;
            List <long> weaknessList  = new List <long>();

            // Iterate through list while looking for consecutive numbers that will sum to the target (invalidNum)
            for (int ii = 0; ii < inputsRaw.Length; ii++)
            {
                if (foundWeakness)
                {
                    break;
                }
                runningSum   = 0;
                runningCount = 0;
                for (int jj = ii; jj < inputsRaw.Length; jj++)
                {
                    if (runningSum > invalidNum)
                    {
                        break;
                    }
                    runningSum += inputsRaw[jj];
                    runningCount++;

                    if (runningSum == invalidNum)
                    {
                        lastId        = jj;
                        foundWeakness = true;
                        break;
                    }
                }
            }

            // Add to list to get min/max
            for (int ii = 0; ii < runningCount; ii++)
            {
                weaknessList.Add(inputsRaw[lastId - ii]);
            }
            long weakness = weaknessList.Min() + weaknessList.Max();

            return(weakness.ToString());
        }
Example #17
0
        public string SolveP1()
        {
            long[] inputsRaw     = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).ToList().Select(x => long.Parse(x)).ToArray();
            int    preambleCount = 25;
            long   invalidNum    = long.MinValue;

            // Iterate through array starting from the 25th (preamble) element
            //  On each element, iterate the preceeding 25 elements while checking to see if any two elements sum up to next number
            for (int ii = preambleCount - 1; ii < inputsRaw.Length - 1; ii++)
            {
                Boolean validNext = false;
                for (int jj = 0; jj < preambleCount; jj++)
                {
                    // If a previous number is larger than target number, skip (no negatives so impossible to sum)
                    if (inputsRaw[ii - jj] > inputsRaw[ii + 1])
                    {
                        continue;
                    }

                    for (int kk = 1; kk < preambleCount; kk++)
                    {
                        // If indices are the same or a previous number is larger than target number, skip (no negatives so impossible to sum)
                        if (jj == kk || inputsRaw[ii - kk] > inputsRaw[ii + 1])
                        {
                            continue;
                        }
                        if (inputsRaw[ii - jj] + inputsRaw[ii - kk] == inputsRaw[ii + 1])
                        {
                            validNext = true;
                            break;
                        }
                    }

                    if (validNext)
                    {
                        break;
                    }
                }

                if (!validNext)
                {
                    invalidNum = inputsRaw[ii + 1];
                    break;
                }
            }

            return(invalidNum.ToString());
        }
Example #18
0
        public string SolveP2_Old()
        {
            List <int> inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).Select(x => Int32.Parse(x)).ToList();

            inputsRaw.Add(0);
            inputsRaw.Add(inputsRaw.Max() + 3);
            inputsRaw.Sort();

            // Makes a dictionary of dependencies
            //  key: adapter joltage | value: list of valid adapters in list of adapters
            Dictionary <int, List <int> > adapterDependencies = new Dictionary <int, List <int> >();

            for (int ii = 0; ii < inputsRaw.Count(); ii++)
            {
                int        currMax   = inputsRaw[ii] + 3;
                List <int> validNums = new List <int>();
                int        jj        = ii + 1;
                while (jj < inputsRaw.Count() && inputsRaw[jj] <= currMax)
                {
                    validNums.Add(inputsRaw[jj]);
                    jj++;
                }
                adapterDependencies.Add(inputsRaw[ii], validNums);
            }

            // Use a queue to maintain dependencies
            //  Enqueue all dependencies of a "node" | Dequeue on processed
            //  Only viable for small inputs, slow and space consuming
            Queue <int> queue = new Queue <int>();

            queue.Enqueue(0);
            int count = 1;

            while (queue.Count > 0)
            {
                int currAdapter = queue.Dequeue();
                if (adapterDependencies[currAdapter].Count() > 1)
                {
                    count += adapterDependencies[currAdapter].Count() - 1;
                }
                foreach (int currDepends in adapterDependencies[currAdapter])
                {
                    queue.Enqueue(currDepends);
                }
            }

            return(count.ToString());
        }
Example #19
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        //Setup
        int  last     = 0;
        bool wasFirst = true;
        int  turn     = this.Data.Values.Max();
        Dictionary <int, int> previous = new();

        //Part 1
        GetToTarget(ref turn, ref wasFirst, ref last, FIRST_TARGET, previous);
        AoCUtils.LogPart1(last);

        //Part 2 (takes a couple seconds but who cares)
        GetToTarget(ref turn, ref wasFirst, ref last, SECOND_TARGET, previous);
        AoCUtils.LogPart2(last);
    }
Example #20
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        //Part one decoding
        Dictionary <long, long> memory = new();
        Bitmask bitmask = default;

        this.Data.ForEach(i => i.Execute(memory, ref bitmask));
        AoCUtils.LogPart1(memory.Values.Sum());

        //Part two decoding
        memory.Clear();
        Bitmask bitmaskV2 = default;

        this.Data.ForEach(i => i.ExecuteV2(memory, ref bitmaskV2));
        AoCUtils.LogPart2(memory.Values.Sum());
    }
Example #21
0
        public string SolveP1()
        {
            string[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3));

            int maxId  = 0;
            int maxRow = 127;
            int maxCol = 7;

            foreach (string currLine in inputsRaw)
            {
                double rowStart = 0;
                double rowEnd   = maxRow;
                for (int ii = 0; ii < 7; ii++)
                {
                    if (currLine[ii] == 'F')
                    {
                        rowEnd = rowEnd - Math.Ceiling((rowEnd - rowStart) / 2);
                    }
                    else
                    {
                        rowStart = rowStart + Math.Ceiling((rowEnd - rowStart) / 2);
                    }
                }

                double colStart = 0;
                double colEnd   = maxCol;
                for (int ii = 7; ii < currLine.Length; ii++)
                {
                    if (currLine[ii] == 'L')
                    {
                        colEnd = colEnd - Math.Ceiling((colEnd - colStart) / 2);
                    }
                    else
                    {
                        colStart = colStart + Math.Ceiling((colEnd - colStart) / 2);
                    }
                }

                int currId = (int)(rowStart * 8 + colStart);
                if (currId > maxId)
                {
                    maxId = currId;
                }
            }

            return(maxId.ToString());
        }
Example #22
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        // Check the one window differences
        int total = 0;

        foreach (int i in 1..Data.Length)
        {
            if (Data[i] > Data[i - 1])
            {
                total++;
            }
        }

        AoCUtils.LogPart1(total);

        // Check the three window differences
        total = 0;
        int previous = Data[..3].Sum();
Example #23
0
        public string SolveP2()
        {
            string[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3), true);

            int runningSum    = 0;
            int groupMemCount = 0;
            Dictionary <char, int> groupAnswers = new Dictionary <char, int>();

            foreach (string currLine in inputsRaw)
            {
                if (currLine == "")
                {
                    int groupSum = 0;
                    foreach (KeyValuePair <char, int> kvp in groupAnswers)
                    {
                        if (kvp.Value == groupMemCount)
                        {
                            groupSum++;
                        }
                    }
                    runningSum += groupSum;

                    groupMemCount = 0;
                    groupAnswers.Clear();
                    continue;
                }

                groupMemCount++;
                foreach (char currAns in currLine)
                {
                    if (groupAnswers.ContainsKey(currAns))
                    {
                        groupAnswers[currAns]++;
                    }
                    else
                    {
                        groupAnswers.Add(currAns, 1);
                    }
                }
            }

            return(runningSum.ToString());
        }
Example #24
0
        public string SolveP2()
        {
            List <int> inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).Select(x => Int32.Parse(x)).ToList();

            inputsRaw.Add(0);
            inputsRaw.Add(inputsRaw.Max() + 3);
            inputsRaw.Sort();

            // Makes a dictionary of dependencies
            //  key: adapter joltage | value: list of valid adapters in list of adapters
            Dictionary <int, List <int> > adapterDependencies = new Dictionary <int, List <int> >();

            for (int ii = 0; ii < inputsRaw.Count(); ii++)
            {
                int        currMax   = inputsRaw[ii] + 3;
                List <int> validNums = new List <int>();
                int        jj        = ii + 1;
                while (jj < inputsRaw.Count() && inputsRaw[jj] <= currMax)
                {
                    validNums.Add(inputsRaw[jj]);
                    jj++;
                }
                adapterDependencies.Add(inputsRaw[ii], validNums);
            }

            // Iterate while maintaining a list of possible permutations
            //  Working backwards, combine the sum of each dependency until the first
            //  Math approach the only viable method for larger inputs
            Dictionary <int, long> permutations = new Dictionary <int, long>();

            permutations.Add(inputsRaw.Max(), 1);
            for (int ii = inputsRaw.Count() - 2; ii >= 0; ii--)
            {
                long currCount = 0;
                foreach (int depend in adapterDependencies[inputsRaw[ii]])
                {
                    currCount += permutations[depend];
                }
                permutations.Add(inputsRaw[ii], currCount);
            }

            return(permutations[0].ToString());;
        }
Example #25
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        long max = long.MinValue;

        //Go through all permutations of part 1 settings
        foreach (long[] perm in AoCUtils.Permutations(part1Phase))
        {
            //Add phase settings
            foreach (int i in..AMPS)
            {
                this.Data[i].AddInput(perm[i]);
            }
            //Add input value
            this.Data[0].AddInput(0L);

            //Run all amplifiers
            this.Data.ForEach(amp => amp.Run());

            //Get value from last amplifier
            max = Math.Max(max, this.Data[^ 1].GetNextOutput());
Example #26
0
        public Dictionary <string, List <Tuple <string, int> > > createBagOfMadness()
        {
            string[] inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3));
            Dictionary <string, List <Tuple <string, int> > > bagsOfMadness = new Dictionary <string, List <Tuple <string, int> > >();

            foreach (string currLine in inputsRaw)
            {
                string[] components = currLine.Replace(".", "").Split(new string[] { "contain" }, StringSplitOptions.None);
                string   mainBag    = components[0].Trim();
                if (mainBag.EndsWith("s"))
                {
                    mainBag = mainBag.Substring(0, mainBag.Length - 1);
                }
                if (!bagsOfMadness.ContainsKey(mainBag))
                {
                    List <Tuple <string, int> > contents = new List <Tuple <string, int> >();
                    string[] contentsRaw = components[1].Split(',');

                    if (components[1].Trim() == "no other bags")
                    {
                        bagsOfMadness.Add(mainBag, new List <Tuple <string, int> >());
                    }
                    else
                    {
                        foreach (string currContent in contentsRaw)
                        {
                            int    numInd = currContent.Trim().IndexOf(' ');
                            int    numBag = Int32.Parse(currContent.Trim().Substring(0, numInd));
                            string bag    = currContent.Trim().Substring(numInd + 1);
                            if (bag.EndsWith("s"))
                            {
                                bag = bag.Substring(0, bag.Length - 1);
                            }
                            contents.Add(new Tuple <string, int>(bag, numBag));
                        }
                        bagsOfMadness.Add(mainBag, contents);
                    }
                }
            }
            return(bagsOfMadness);
        }
Example #27
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        //Start moving the cups
        LinkedListNode <int> current = MoveCups(this.Data, PART1_MOVES).NextCircular();
        //Get resulting string
        StringBuilder builder = new(this.Data.Length - 1);

        while (current.Value is not 1)
        {
            builder.Append(current.Value);
            current = current.NextCircular();
        }
        AoCUtils.LogPart1(builder);

        //Create large cups array
        int[] largeData = Enumerable.Range(1, AMOUNT).ToArray();
        this.Data.CopyTo(largeData, 0);
        //Move cups and get result
        current = MoveCups(largeData, PART2_MOVES).NextCircular();
        AoCUtils.LogPart2((long)current.Value * current.NextCircular().Value);
    }
Example #28
0
        public string SolveP1()
        {
            string[] inputsRaw   = AoCUtils.readInputFile(this.GetType().Name.Substring(3));
            int[]    instStatus  = new int[inputsRaw.Length];
            int      currLine    = 0;
            int      accumulator = 0;

            while (instStatus[currLine] == 0)
            {
                instStatus[currLine] = 1;
                if (inputsRaw[currLine].StartsWith("nop"))
                {
                    currLine++;
                    continue;
                }

                string[] components = inputsRaw[currLine].Split(' ');
                int      multiplier = 1;
                if (components[1][0] == '-')
                {
                    multiplier = -1;
                }

                int num = Int32.Parse(components[1].Substring(1)) * multiplier;

                switch (components[0])
                {
                case "acc":
                    accumulator += num;
                    currLine++;
                    break;

                case "jmp":
                    currLine += num;
                    break;
                }
            }

            return(accumulator.ToString());
        }
Example #29
0
    /// <inheritdoc cref="Solver.Run"/>
    public override void Run()
    {
        (this.VM[1], this.VM[2]) = (12L, 2L);
        this.VM.Run();
        AoCUtils.LogPart1(this.VM[0]);

        foreach (int noun in..MAX)
        {
            foreach (int verb in..MAX)
            {
                this.VM.Reset();
                (this.VM[1], this.VM[2]) = (noun, verb);
                this.VM.Run();
                if (this.VM[0] is not TARGET)
                {
                    continue;
                }

                AoCUtils.LogPart2((100 * noun) + verb);
                return;
            }
        }
    }
Example #30
0
        public string SolveP1()
        {
            List <int> inputsRaw = AoCUtils.readInputFile(this.GetType().Name.Substring(3)).Select(x => Int32.Parse(x)).ToList();

            inputsRaw.Sort();

            int joltDiff1   = 0;
            int joltDiff3   = 0;
            int currentJolt = 0;

            // Since maximum number of adapters needs to be used, sort list first
            // Iterate and make sure each adapter is "valid" (at most three away)
            //  while counting the instances of diff1 and diff3
            foreach (int iterJolt in inputsRaw)
            {
                int currDiff = iterJolt - currentJolt;
                if (currDiff <= 3)
                {
                    switch (currDiff)
                    {
                    case 1:
                        joltDiff1++;
                        break;

                    case 3:
                        joltDiff3++;
                        break;
                    }
                    currentJolt = iterJolt;
                }
            }

            // Plus one to diff3 in order to account for device adapter
            int result = joltDiff1 * (joltDiff3 + 1);

            return(result.ToString());
        }