Пример #1
0
        public static void Run()
        {
            List <string> linesInput = File.ReadAllLines(Util.ReadFromInputFolder(21)).ToList();

            int controlPointer = Convert.ToInt32(linesInput.First().Between("#ip "));

            linesInput.RemoveAt(0);
            int instructionPosition = 0;

            foreach (string line in linesInput)
            {
                string[] lineInstruc           = line.Split(' ');
                Tuple <string, int[]> instruct = new Tuple <string, int[]>(lineInstruc[0], new int[6]);
                instruct.Item2[1] = Convert.ToInt32(lineInstruc[1]);
                instruct.Item2[2] = Convert.ToInt32(lineInstruc[2]);
                instruct.Item2[3] = Convert.ToInt32(lineInstruc[3]);
                dctInstructions.Add(instructionPosition, instruct);
                instructionPosition++;
            }

            Dictionary <int, int> uniqueValues = new Dictionary <int, int>();
            bool printPartOne = false;

            int indexToWatch   = 0;
            var keyInstruction = dctInstructions[28];

            if (keyInstruction.Item1 == "eqrr" && (keyInstruction.Item2[1] == 0 || keyInstruction.Item2[2] == 0))
            {
                indexToWatch = Math.Max(keyInstruction.Item2[1], keyInstruction.Item2[2]);
            }

            Console.WriteLine("Computing both parts, part 2 takes a while");

            while (true)
            {
                if (baseRegister[controlPointer] == 28)
                {
                    if (printPartOne == false)
                    {
                        Console.WriteLine("PART 1: " + baseRegister[indexToWatch]);
                        printPartOne = true;
                    }
                    if (uniqueValues.ContainsKey(baseRegister[indexToWatch]) == false)
                    {
                        uniqueValues.Add(baseRegister[indexToWatch], baseRegister[indexToWatch]);
                    }
                    else
                    {
                        Console.WriteLine("PART 2: " + uniqueValues.Last().Key);
                        break;
                    }
                }

                var currRegister = dctInstructions[baseRegister[controlPointer]];
                ExecuteInstruction(currRegister.Item1, currRegister.Item2);
                baseRegister[controlPointer] = (baseRegister[controlPointer] + 1);
            }

            Console.ReadLine();
        }
Пример #2
0
        public static void Run()
        {
            string[] linesInput       = File.ReadAllLines(Util.ReadFromInputFolder(7));
            string   problem1Solution = Problem1(linesInput);

            Console.WriteLine(problem1Solution);
            Console.WriteLine(Problem2(linesInput, problem1Solution));
        }
Пример #3
0
        public static void Run()
        {
            string[]  linesInput = File.ReadAllLines(Util.ReadFromInputFolder(8));
            QuirkNode baseNode;

            Console.WriteLine(Problem1(linesInput, out baseNode));
            Console.WriteLine(Problem2(baseNode));
        }
Пример #4
0
        public static void Run()
        {
            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(24));
            ParseInput(linesInput);

            int  minimumBoostToWin = 0;
            bool keepBoosting      = true;

            List <UnitGroup> copyOfCombatants = lstCombatants.ConvertAll(Unit => new UnitGroup(Unit));

            int staleMateLimit = 15;

            while (keepBoosting)
            {
                int staleMateCount = 0;
                lstCombatants = copyOfCombatants.ConvertAll(Unit => new UnitGroup(Unit));
                lstCombatants.Where(r => r.faction == Faction.InmuneSystem).ForEach(r => r.attackPower = r.attackPower + minimumBoostToWin);

                int lastTurnTotal = lstCombatants.Sum(r => r.unitsAmount);

                bool gameFinished = false;
                while (gameFinished == false)
                {
                    TargetSelectionLogic();
                    CombatLogic();
                    gameFinished = EndCondition();
                    if (lastTurnTotal == lstCombatants.Sum(r => r.unitsAmount))
                    {
                        if (staleMateCount == staleMateLimit)
                        {
                            break;
                        }
                        else
                        {
                            staleMateCount++;
                        }
                    }
                    else
                    {
                        lastTurnTotal = lstCombatants.Sum(r => r.unitsAmount);
                    }
                }

                if (minimumBoostToWin == 0)
                {
                    Console.WriteLine("PART 1: " + lstCombatants.Sum(r => r.unitsAmount));
                }

                if (lstCombatants.All(r => r.faction == Faction.InmuneSystem))
                {
                    Console.WriteLine("DEER SURVIVES, Boost: " + minimumBoostToWin);
                    Console.WriteLine("PART 2: " + lstCombatants.Sum(r => r.unitsAmount));
                    keepBoosting = false;
                    break;
                }
                minimumBoostToWin += 1;
            }
        }
Пример #5
0
        public static void Run()
        {
            dctMap.Add(new Point(500, 500), '.');
            GetAllSurroundings(player);

            string linesInput = File.ReadAllLines(Util.ReadFromInputFolder(20))[0];

            foreach (char C in linesInput)
            {
                if (C == '(')
                {
                    parenthesisStack.Push('(');
                    lastPositionStack.Push(player);
                }
                else if (C == ')')
                {
                    parenthesisStack.Pop();
                    player = lastPositionStack.Pop();
                }
                else if (C == '|')
                {
                    player = lastPositionStack.Peek();
                }
                else
                {
                    Logic(C);
                    GetAllSurroundings(player);
                }
            }

            ClearUnknown();

            // Using DAY15 Pathfinding, since doors and rooms both count as open spaces we need to
            // cut the total of cost in half
            Dictionary <Point, PrevPoint> dctPoints = new Dictionary <Point, PrevPoint>();

            PathFinding(new Point(500, 500), dctPoints, 0);
            var elementor = (dctPoints.OrderByDescending(r => r.Value.cost).First().Value.cost) / 2;

            Console.WriteLine("PART 1: " + elementor);

            // Unlike the maximum cost room, there might be multiple in this category and dividing by 2
            // could produce off by 1 errors so we will have to count them manually
            var prelimList      = dctPoints.Where(r => r.Value.cost >= 2000).ToList();
            int properRoomCount = 0;

            foreach (var prelim in prelimList)
            {
                if (dctMap[prelim.Key] == '.')
                {
                    properRoomCount++;
                }
            }
            Console.WriteLine("PART 2: " + properRoomCount);
        }
Пример #6
0
        public static void Run()
        {
            string[] linesInput      = File.ReadAllLines(Util.ReadFromInputFolder(9));
            string   INPUT           = linesInput[0];
            var      inputArray      = INPUT.Split(' ');
            int      numberOfPlayers = Convert.ToInt32(inputArray[0]);
            long     marbles         = Convert.ToInt32(inputArray[6]);

            Console.WriteLine(Problem1(numberOfPlayers, marbles));
            Console.WriteLine(Problem2(numberOfPlayers, marbles));
        }
Пример #7
0
        public static void Run()
        {
            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(25));
            foreach (string line in linesInput)
            {
                string[] pPoint = line.Split(',');
                long     pX     = Convert.ToInt64(pPoint[0].Trim());
                long     pY     = Convert.ToInt64(pPoint[1].Trim());
                long     pZ     = Convert.ToInt64(pPoint[2].Trim());
                long     pA     = Convert.ToInt64(pPoint[3].Trim());
                stars.Add(new fPoint(pX, pY, pZ, pA));
            }

            while (stars.Count() > 0)
            {
                var leStar = stars.First();
                if (constellations.Count == 0)
                {
                    constellations.Add(new List <fPoint>());
                    constellations.First().Add(leStar);
                }
                else
                {
                    var starGroup = constellations.Where(r => r.Any(wr => ManhattanDist(leStar, wr) <= 3));
                    if (starGroup.Count() > 0)
                    {
                        if (starGroup.Count() > 1)
                        {
                            var leJoinFactor = starGroup.First();
                            foreach (var littleStar in starGroup.Skip(1))
                            {
                                leJoinFactor.AddRange(littleStar);
                                littleStar.Clear();
                            }
                            leJoinFactor.Add(leStar);
                        }
                        else
                        {
                            starGroup.Last().Add(leStar);
                        }
                    }
                    else
                    {
                        constellations.Add(new List <fPoint>());
                        constellations.Last().Add(leStar);
                    }
                }
                stars.RemoveAt(0);
            }

            Console.WriteLine("PART 1: " + constellations.Where(r => r.Count() > 0).Count());
        }
Пример #8
0
        public static void Run(string path = null)
        {
            List <string> linesInput = File.ReadAllLines(Util.ReadFromInputFolder(13)).ToList();
            int           Height     = linesInput.Count();
            int           Width      = linesInput.OrderByDescending(r => r.Length).First().Length;

            int leCartID = 1;

            char[,] grid = new char[Width, Height];

            int j = 0;

            foreach (string line in linesInput)
            {
                for (int w = 0; w < line.Count(); w++)
                {
                    if (isCart(line[w]))
                    {
                        lstCarts.Add(new Minecart(leCartID, w, j, (Direction)line[w]));
                        if ((Direction)line[w] == Direction.Down || (Direction)line[w] == Direction.Up)
                        {
                            grid[w, j] = '|';
                        }
                        else
                        {
                            grid[w, j] = '-';
                        }
                        leCartID++;
                    }
                    else
                    {
                        grid[w, j] = line[w];
                    }
                }
                j++;
            }
            while (true)
            {
                foreach (Minecart cart in lstCarts.OrderBy(r => r.positionX))
                {
                    cart.moveAhead(grid);
                }
                Ticks++;
                if (lstCarts.Count == 1)
                {
                    //Console.WriteLine("LAST CART: [" + lstCarts.First().positionX + "][" + lstCarts.First().positionY + "]");
                    Console.WriteLine("PART 2: " + lstCarts.First().positionX + "," + lstCarts.First().positionY);
                    break;
                }
            }
        }
Пример #9
0
        public static void Run()
        {
            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(23));
            foreach (string line in linesInput)
            {
                string[] posCoords      = line.Between("<", ">").Split(',');
                long     signalStrength = Convert.ToInt64(line.Between("r=").Trim());
                long     xPoint         = Convert.ToInt64(posCoords[0]);
                long     yPoint         = Convert.ToInt64(posCoords[1]);
                long     zPoint         = Convert.ToInt64(posCoords[2]);
                fPoint   BotPosition    = new fPoint(xPoint, yPoint, zPoint);
                dctNanoBots.Add(BotPosition, signalStrength);
            }

            var strongestNano = dctNanoBots.OrderByDescending(r => r.Value).First();

            Console.WriteLine("Part 1: " + dctNanoBots.Where(r => ManhattanDist(r.Key, strongestNano.Key) <= strongestNano.Value).Count());
            Console.WriteLine("Loading part 2, should take 1 minute");

            // Reduces the lookout on the points to make complexity manageable
            // Finds best match for this small region
            // Amplifies the result to set it up for the next factor
            fPoint lePoint = new fPoint();

            for (int factor = 10000000; factor >= 1; factor /= 10)
            {
                lePoint    = OperateDict(reduceDict(factor), lePoint);
                lePoint.X *= 10;
                lePoint.Y *= 10;
                lePoint.Z *= 10;
            }
            string answer = ManhattanDist(new fPoint(0, 0, 0), lePoint).ToString();

            answer = answer.Remove(answer.Length - 1); //remove last character for the last extra computation
            Console.WriteLine("Part 2: " + answer);
        }
Пример #10
0
 public static void Run()
 {
     string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(2));
     Console.WriteLine(Problem1(linesInput));
     Console.WriteLine(Problem2(linesInput));
 }
Пример #11
0
        public static void Run()
        {
            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(18));

            width  = linesInput[0].Length;
            height = linesInput.Count();

            int j = 0;

            foreach (string line in linesInput)
            {
                for (int w = 0; w < line.Count(); w++)
                {
                    dctMap.Add(new Point(w, j), line[w]);
                }
                j++;
            }

            int Minutes = 1000000000;

            for (int i = 0; i < Minutes; i++)
            {
                dctFutureMap.Clear();
                foreach (var element in dctMap)
                {
                    MorphLogic(element.Key);
                }
                var futureGen = new Dictionary <Point, char>(dctFutureMap);
                dctMap = futureGen;
                string uniqueDct = DctAsString();
                if (dctRepetitions.ContainsKey(uniqueDct) == false)
                {
                    dctRepetitions.Add(uniqueDct, i);
                }
                else
                {
                    int minInitial     = dctRepetitions[uniqueDct];
                    int currRepetition = i;

                    Console.WriteLine("Repetition detected at: " + i);
                    Console.WriteLine("Originally found first at: " + minInitial);
                    Console.WriteLine("Cycles each: " + (i - minInitial));

                    //Detecting which repetition cycle corresponds to the target
                    //offset by -1, since 0 start index and we breakin'
                    for (int w = minInitial; w < i; w++)
                    {
                        if ((Minutes - w) % (i - minInitial) == 0)
                        {
                            var leValue = dctRepetitions.Single(R => R.Value == w - 1).Key.ToList();
                            Console.WriteLine("PART 2: " + leValue.Count(r => r == lumberyard) * leValue.Count(r => r == trees));
                        }
                    }
                    break;
                }
            }

            //offset by -1, since 0 start index
            int lumberValue = dctRepetitions.Single(R => R.Value == 9).Key.ToList().Count(r => r == lumberyard);
            int woodValue   = dctRepetitions.Single(R => R.Value == 9).Key.ToList().Count(r => r == trees);

            Console.WriteLine("PART 1: " + (lumberValue * woodValue));
        }
Пример #12
0
        public static void Run()
        {
            List <string> linesInputFirst  = File.ReadAllLines(Util.ReadFromInputFolder("16_A")).Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();
            List <string> linesInputSecond = File.ReadAllLines(Util.ReadFromInputFolder("16_B")).ToList();

            int countBehavior = 0;

            string[] opBase = new string[]
            { "addi", "addr", "bani", "banr",
              "bori", "borr", "eqir", "eqri",
              "eqrr", "gtir", "gtri", "gtrr",
              "muli", "mulr", "seti", "setr" };
            for (int i = 0; i < 16; i++)
            {
                opCodeDict.Add(i, new List <string>(opBase));
            }

            //part 1
            while (linesInputFirst.Count > 0)
            {
                string line1 = linesInputFirst.First();
                string line2 = linesInputFirst.Skip(1).First();
                string line3 = linesInputFirst.Skip(2).First();
                linesInputFirst.RemoveRange(0, 3);

                string[] lin1array = line1.Between("[", "]").Split(',');
                string[] lin3array = line3.Between("[", "]").Split(',');

                int[] input          = Array.ConvertAll(lin1array, s => Convert.ToInt32(s.Trim()));
                int[] instruction    = Array.ConvertAll(line2.Split(' '), s => Convert.ToInt32(s.Trim()));
                int[] expectedOutput = Array.ConvertAll(lin3array, s => Convert.ToInt32(s.Trim()));

                FigureOutCodes(input, instruction, expectedOutput);
                if (part1Check(input, instruction, expectedOutput))
                {
                    countBehavior++;
                }
            }

            //part 2 figure the registers
            while (opCodeDict.Any(r => r.Value.Count > 1))
            {
                var orderedCandidates = opCodeDict.OrderBy(r => r.Value.Count);
                foreach (var pair in orderedCandidates)
                {
                    if (pair.Value.Count == 1)
                    {
                        opCodeDict.Where(r => r.Key != pair.Key).AsParallel().ForAll(r => r.Value.RemoveAll(w => w == pair.Value.First()));
                    }
                }
            }

            //part 2 run program
            int[] baseRegister = new int[4] {
                0, 0, 0, 0
            };
            foreach (string line in linesInputSecond)
            {
                int[]  instruction = Array.ConvertAll(line.Split(' '), s => Convert.ToInt32(s.Trim()));
                string opCode      = opCodeDict[instruction[0]].First();
                if (opCode == "addi")
                {
                    baseRegister = AsmEmu.addi(baseRegister, instruction);
                }
                else if (opCode == "addr")
                {
                    baseRegister = AsmEmu.addr(baseRegister, instruction);
                }
                else if (opCode == "bani")
                {
                    baseRegister = AsmEmu.bani(baseRegister, instruction);
                }
                else if (opCode == "banr")
                {
                    baseRegister = AsmEmu.banr(baseRegister, instruction);
                }
                else if (opCode == "bori")
                {
                    baseRegister = AsmEmu.bori(baseRegister, instruction);
                }
                else if (opCode == "borr")
                {
                    baseRegister = AsmEmu.borr(baseRegister, instruction);
                }
                else if (opCode == "eqir")
                {
                    baseRegister = AsmEmu.eqir(baseRegister, instruction);
                }
                else if (opCode == "eqri")
                {
                    baseRegister = AsmEmu.eqri(baseRegister, instruction);
                }
                else if (opCode == "eqrr")
                {
                    baseRegister = AsmEmu.eqrr(baseRegister, instruction);
                }
                else if (opCode == "gtir")
                {
                    baseRegister = AsmEmu.gtir(baseRegister, instruction);
                }
                else if (opCode == "gtri")
                {
                    baseRegister = AsmEmu.gtri(baseRegister, instruction);
                }
                else if (opCode == "gtrr")
                {
                    baseRegister = AsmEmu.gtrr(baseRegister, instruction);
                }
                else if (opCode == "muli")
                {
                    baseRegister = AsmEmu.muli(baseRegister, instruction);
                }
                else if (opCode == "mulr")
                {
                    baseRegister = AsmEmu.mulr(baseRegister, instruction);
                }
                else if (opCode == "seti")
                {
                    baseRegister = AsmEmu.seti(baseRegister, instruction);
                }
                else if (opCode == "setr")
                {
                    baseRegister = AsmEmu.setr(baseRegister, instruction);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            Console.WriteLine("PART 1: " + countBehavior);
            Console.WriteLine("PART 2: " + baseRegister[0] + " " + baseRegister[1] + " " + baseRegister[2] + " " + baseRegister[3]);
        }
Пример #13
0
        public static void Run()
        {
            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(10));

            List <SkyLight> lstLights = new List <SkyLight>();

            Point maxPoint = new Point(999999, 999999);

            foreach (string line in linesInput)
            {
                var      rawInfoPosition = line.Between("tion=<", "> velo");
                string[] positionArray   = rawInfoPosition.Split(',');
                var      rawInfoSpeed    = line.Between("velocity=<", ">");
                string[] speedArray      = rawInfoSpeed.Split(',');

                Point startPosition = new Point(Convert.ToInt32(positionArray[0].Trim()), Convert.ToInt32(positionArray[1].Trim()));
                Point speed         = new Point(Convert.ToInt32(speedArray[0].Trim()), Convert.ToInt32(speedArray[1].Trim()));

                lstLights.Add(new SkyLight(startPosition, speed));
            }

            int seconds = 0;

            while (true)
            {
                foreach (SkyLight light in lstLights)
                {
                    light.Tick();
                }

                int currentMaxX = lstLights.Max(r => r.position.X);
                int currentMaxY = lstLights.Max(r => r.position.Y);

                if (currentMaxX < maxPoint.X && currentMaxY < maxPoint.Y)
                {
                    maxPoint = new Point(currentMaxX, currentMaxY);
                }
                else
                {
                    Console.WriteLine(seconds);
                    break;
                }
                seconds++;

                /*
                 * if (lstLights.GroupBy(r => r.position.X).Where(w => w.Count() >= 10).Count() >= 10)
                 * {
                 *  leCondition = false;
                 *  Console.WriteLine(seconds);
                 * }*/
            }

            foreach (SkyLight light in lstLights)
            {
                light.TickBackwards();
            }

            int minX = lstLights.Min(r => r.position.X);
            int minY = lstLights.Min(r => r.position.Y);
            int maxX = lstLights.Max(r => r.position.X);
            int maxY = lstLights.Max(r => r.position.Y);

            StringBuilder sb = new StringBuilder();

            for (int j = minY; j < maxY + 1; j++)
            {
                sb.Clear();
                for (int i = minX; i < maxX + 1; i++)
                {
                    if (lstLights.Where(r => r.position.X == i && r.position.Y == j).Count() > 0)
                    {
                        sb.Append('#');
                    }
                    else
                    {
                        sb.Append('.');
                    }
                }
                Console.WriteLine(sb.ToString());
            }
        }
Пример #14
0
        public static void Run()
        {
            List <string> linesInput = File.ReadAllLines(Util.ReadFromInputFolder(19)).ToList();

            int controlPointer = Convert.ToInt32(linesInput.First().Between("#ip "));

            linesInput.RemoveAt(0);
            int instructionPosition = 0;

            foreach (string line in linesInput)
            {
                string[] lineInstruc           = line.Split(' ');
                Tuple <string, int[]> instruct = new Tuple <string, int[]>(lineInstruc[0], new int[6]);
                instruct.Item2[1] = Convert.ToInt32(lineInstruc[1]);
                instruct.Item2[2] = Convert.ToInt32(lineInstruc[2]);
                instruct.Item2[3] = Convert.ToInt32(lineInstruc[3]);
                dctInstructions.Add(instructionPosition, instruct);
                instructionPosition++;
            }

            while (true)
            {
                if (dctInstructions.ContainsKey(baseRegister[controlPointer]) == false)
                {
                    break;
                }

                var currRegister = dctInstructions[baseRegister[controlPointer]];
                ExecuteInstruction(currRegister.Item1, currRegister.Item2);
                baseRegister[controlPointer] = (baseRegister[controlPointer] + 1);
            }

            Console.WriteLine("PART 1: " + baseRegister[0] + " " + baseRegister[1] + " " + baseRegister[2] + " " + baseRegister[3] + " " + baseRegister[4] + " " + baseRegister[5]);

            //Find out which register do i need the sum of factors for
            int chosenRegistry = 0;

            for (int i = 1; i < 6; i++)
            {
                if (baseRegister[0] == Util.divSum(baseRegister[i]))
                {
                    chosenRegistry = i;
                    break;
                }
            }

            baseRegister    = new int[6];
            baseRegister[0] = 1;
            for (int i = 0; i < 1000; i++)
            {
                if (dctInstructions.ContainsKey(baseRegister[controlPointer]) == false)
                {
                    break;
                }

                var currRegister = dctInstructions[baseRegister[controlPointer]];
                ExecuteInstruction(currRegister.Item1, currRegister.Item2);
                baseRegister[controlPointer] = (baseRegister[controlPointer] + 1);
            }
            Console.WriteLine("PART 2: " + Util.divSum(baseRegister[chosenRegistry]));
        }
Пример #15
0
        public static bool SimulateBattle(int elvenPower = 3)
        {
            lstUnits   = new List <Unit>();
            FinishGame = false;

            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(15));
            int      Height     = linesInput.Count();
            int      Width      = linesInput.OrderByDescending(r => r.Length).First().Length;

            grid = new char[Width, Height];

            int j  = 0;
            int ID = 1;

            foreach (string line in linesInput)
            {
                for (int w = 0; w < line.Count(); w++)
                {
                    if (line[w] == 'G' || line[w] == 'E')
                    {
                        grid[w, j] = '.';
                        if (line[w] == 'G')
                        {
                            lstUnits.Add(new Unit(ID, new Point(w, j), Faction.Goblin));
                        }
                        else
                        {
                            lstUnits.Add(new Unit(ID, new Point(w, j), Faction.Elf, elvenPower));
                        }
                        ID++;
                    }
                    else
                    {
                        grid[w, j] = line[w];
                    }
                }
                j++;
            }

            int originalAmountOfElves = lstUnits.Where(r => r.faction == Faction.Elf).Count();

            int Round = 0;

            PrintMap(Width, Height, grid);
            while (FinishGame == false)
            {
                var orderedUnits = lstUnits.OrderBy(r => r.Position.Y).ThenBy(r => r.Position.X);
                foreach (Unit soldier in orderedUnits)
                {
                    if (soldier.HP <= 0)
                    {
                        continue;
                    }
                    Logic(soldier);
                    if (FinishGame == true)
                    {
                        break;
                    }
                }
                PrintMap(Width, Height, grid);
                if (FinishGame == false)
                {
                    Round++;
                }
            }

            if (lstUnits.Where(r => r.faction == Faction.Elf).Count() == originalAmountOfElves)
            {
                Console.WriteLine("TRUE: " + lstUnits.Sum(r => r.HP) * Round + " | ElvenPower=" + elvenPower);
                return(true);
            }
            else
            {
                Console.WriteLine("FALSE: " + lstUnits.Sum(r => r.HP) * Round + " | ElvenPower=" + elvenPower);
                return(false);
            }
        }
Пример #16
0
 public static void Run()
 {
     string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(3));
     Problem1(linesInput);
     Problem2(linesInput);
 }
Пример #17
0
        public static void Run(string path = null)
        {
            StringBuilder sb = new StringBuilder();
            List <string> linesInput;

            if (path == null)
            {
                linesInput = File.ReadAllLines(Util.ReadFromInputFolder(12)).ToList();
            }
            else
            {
                linesInput = File.ReadAllLines(path).ToList();
            }
            string baseGeneration = linesInput[0].Between("initial state: ");

            //Prepare initial state
            int             potCounter = 0;
            List <PotPlant> lstPots    = new List <PotPlant>();

            foreach (char A in baseGeneration)
            {
                lstPots.Add(new PotPlant(potCounter, A));
                potCounter++;
            }

            //Get rid of consumed lines
            linesInput.RemoveAt(0);
            linesInput.RemoveAt(0);

            Dictionary <string, string> producePlantsCombo = new Dictionary <string, string>();
            Dictionary <string, string> killPlantsCombo    = new Dictionary <string, string>();

            LinkedList <long> SameDifferences = new LinkedList <long>();

            long mysteryConstant = 0;

            //Get sprout n wither combinations
            foreach (string line in linesInput)
            {
                //#.... => .
                string[] initialInput  = line.Split(' ');
                string   potCombi      = initialInput[0]; //Pot Combination
                string   producesPlant = initialInput[2]; //Produces plant or not
                if (producesPlant == "#")
                {
                    producePlantsCombo.Add(potCombi, potCombi);
                }
                else
                {
                    killPlantsCombo.Add(potCombi, potCombi);
                }
            }

            LinkedList <PotPlant> llBaseGeneration = new LinkedList <PotPlant>(lstPots);

            var firstElement = llBaseGeneration.First;

            //Extra room left n' right
            for (int i = -20; i < 0; i++)
            {
                llBaseGeneration.AddBefore(firstElement, new PotPlant(i));
            }
            int lastPotNumber = llBaseGeneration.Last().potNumber;

            for (int i = lastPotNumber + 1; i < lastPotNumber + 1000; i++)
            {
                llBaseGeneration.AddLast(new PotPlant(i));
            }

            for (long Gens = 1; Gens < 501; Gens++)
            {
                var lastGeneration = llBaseGeneration;
                LinkedList <PotPlant> upComingGeneration = new LinkedList <PotPlant>();
                var currentNode = llBaseGeneration.First;
                for (int i = 0; i < llBaseGeneration.Count; i++)
                {
                    string plantConfig = ConstructPotStructure(currentNode);
                    if (producePlantsCombo.ContainsKey(plantConfig))
                    {
                        PotPlant futurePlant = new PotPlant(currentNode.Value.potNumber, '#');
                        upComingGeneration.AddLast(futurePlant);
                    }
                    else
                    {
                        PotPlant futurePlant = new PotPlant(currentNode.Value.potNumber, '.');
                        upComingGeneration.AddLast(futurePlant);
                    }
                    currentNode = currentNode.Next;
                }
                long prevDif = upComingGeneration.Where(r => r.plant == '#').Sum(w => w.potNumber) - llBaseGeneration.Where(r => r.plant == '#').Sum(w => w.potNumber);
                SameDifferences.AddLast(prevDif);
                if (SameDifferences.Any(r => r != prevDif))
                {
                    SameDifferences.Clear();
                }
                else
                {
                    // After some point, the output seems displaced on a constant basis forever
                    // Mystery = TOTAL - (sameDif * Gen)
                    // so
                    // TOTAL = Mystery + (sameDif * Gen)
                    if (SameDifferences.Count >= 4)
                    {
                        long total = upComingGeneration.Where(r => r.plant == '#').Sum(w => w.potNumber);
                        mysteryConstant = total - (SameDifferences.First() * Gens);
                        long part2Result = mysteryConstant + (SameDifferences.First() * 50000000000);
                        Console.WriteLine("part 2: " + part2Result);
                        break;
                    }
                }
                llBaseGeneration = upComingGeneration;
                if (Gens == 20)
                {
                    Console.WriteLine("part 1: " + llBaseGeneration.Where(r => r.plant == '#').Sum(w => w.potNumber));
                }
            }
            Console.ReadLine();
        }
Пример #18
0
        public static void Run()
        {
            string[] linesInput = File.ReadAllLines(Util.ReadFromInputFolder(17));
            //build map
            foreach (string line in linesInput)
            {
                //x=571, y=1864..1875
                //y=1700, x=570..588

                int xValueFrom = -1;
                int xValueTo   = -1;

                int yValueFrom = -1;
                int yValueTo   = -1;

                string[] splitLine = line.Split(',');
                string   leftValue = splitLine[0].Substring(2).Trim();
                if (splitLine[0][0] == 'x')
                {
                    xValueFrom = Convert.ToInt32(leftValue);
                    string[] rightValues = splitLine[1].Trim().Substring(2).Split('.');
                    yValueFrom = Convert.ToInt32(rightValues[0]);
                    yValueTo   = Convert.ToInt32(rightValues[2]);
                    for (int y = yValueFrom; y < yValueTo + 1; y++)
                    {
                        if (dctMap.ContainsKey(new Point(xValueFrom, y)) == false)
                        {
                            dctMap.Add(new Point(xValueFrom, y), '#');
                        }
                    }
                }
                else
                {
                    yValueFrom = Convert.ToInt32(leftValue);
                    string[] rightValues = splitLine[1].Trim().Substring(2).Split('.');
                    xValueFrom = Convert.ToInt32(rightValues[0]);
                    xValueTo   = Convert.ToInt32(rightValues[2]);
                    for (int x = xValueFrom; x < xValueTo + 1; x++)
                    {
                        if (dctMap.ContainsKey(new Point(x, yValueFrom)) == false)
                        {
                            dctMap.Add(new Point(x, yValueFrom), '#');
                        }
                    }
                }
            }

            minYBound = dctMap.Min(r => r.Key.Y);
            maxYBound = dctMap.Max(r => r.Key.Y);
            Queue <Point> waterFlow = new Queue <Point>();

            int  lastHydroCount = 0;
            int  sameCounter    = 0;
            bool keepGoing      = true;

            while (keepGoing)
            {
                waterFlow.Enqueue(new Point(500, minYBound - 1));
                while (waterFlow.Count() > 0)
                {
                    Flow(waterFlow);
                    //Console.WriteLine(hydroCount()); <--really slows it down
                }

                if (lastHydroCount == hydroCount())
                {
                    sameCounter++;
                }
                else
                {
                    sameCounter = 0;
                }
                lastHydroCount = hydroCount();
                if (sameCounter >= 3)
                {
                    keepGoing = false;
                    Console.WriteLine("PART 1: " + lastHydroCount);
                    ClearWet();
                    Console.WriteLine("PART 2: " + hydroCount());
                }
            }
        }