Пример #1
0
        public override string Part2()
        {
            var coordinates = PuzzleInput.Split(new[] { "\r\n" }, StringSplitOptions.None).Select(c => c.Split(new[] { "," }, StringSplitOptions.None)).Select((d, e) => new GridCoordinate()
            {
                xVal = Convert.ToInt32(d[0].Trim()), yVal = Convert.ToInt32(d[1].Trim()), Value = (char)(e + 65)
            }).ToHashSet();

            //Create Grid
            GridStride = Test ? 10 : 400;
            var grid = new Coordinate[GridStride * GridStride];

            Parallel.For(0, GridStride, (x) =>
            {
                Parallel.For(0, GridStride, (y) =>
                {
                    var pixel = new Coordinate()
                    {
                        xVal = x, yVal = y
                    };
                    pixel = GeTotalManhattenDistanceValue(pixel, coordinates);
                    grid[x + (y * GridStride)] = pixel;
                });
            });

            Print(grid);
            return(grid.Where(x => x.Value == '#').Count().ToString());
        }
Пример #2
0
        public override string Part2()
        {
            var Carts       = PuzzleInput.Replace("\r\n", "").Select((c, index) => new { c, index }).Where(d => d.c == '>' || d.c == 'v' || d.c == '<' || d.c == '^').Select((e, eindex) => new Cart(e.index, e.c, eindex + 1)).ToList();
            var coordinates = string.Empty;
            var crash       = false;

            while (!crash)
            {
                List <int> cartsTobeRemoved = new List <int>();
                foreach (var Cart in Carts.OrderBy(c => c.Index))
                {
                    if (Cart.Move().HasValue)
                    {
                        cartsTobeRemoved.AddRange(Carts.Where(c => c.Index == Cart.Index).Select(c => c.ID).ToList());
                    }
                    ;
                }
                Carts.RemoveAll(c => cartsTobeRemoved.Contains(c.ID));

                if (Carts.Count == 1)
                {
                    coordinates = GetCoordinates(Carts.First().Index);
                    crash       = true;
                }
                if (Test)
                {
                    Print();
                }
            }
            return(coordinates);
        }
Пример #3
0
        public override async Task Part2()
        {
            var allPuzzleLines = PuzzleInput.Split("\r\n");
            var length         = allPuzzleLines.First().Length;
            var height         = allPuzzleLines.Count();
            var maxCoordinate  = new Coordinate()
            {
                X = length, Y = height
            };

            for (int verticalLine = 0; verticalLine < maxCoordinate.Y; verticalLine++)
            {
                for (int horizontalLine = 0; horizontalLine < maxCoordinate.X; horizontalLine++)
                {
                    var drawing = allPuzzleLines[verticalLine][horizontalLine];
                    if (drawing == '#')
                    {
                        Astroids.Add(new Astroid(horizontalLine, verticalLine));
                    }
                }
            }

            foreach (var astroid in Astroids)
            {
                astroid.TryLookAtAstroids(Astroids.Where(x => x != astroid).ToList());
            }
            var bestAstroid = Astroids.OrderByDescending(x => x.VisibleAstroids.Count).First();

            ResultPart2 = bestAstroid.Vaporize200Astroids();
        }
Пример #4
0
        public override string Part2()
        {
            var testChars = PuzzleInput.ToUpper().Distinct().ToHashSet();

            var polymerLength = PuzzleInput.Count();

            Parallel.ForEach(testChars, (testChar) =>
            {
                var shifts = PuzzleInput.ToList();

                //Remove 1 problem causing polymer
                shifts.RemoveAll(c => c == testChar || c == (char)(testChar + 32));
                bool changed;
                do
                {
                    changed = false;
                    for (int i = 0; i < shifts.Count() - 1; i++)
                    {
                        if ((shifts[i] - shifts[i + 1]) % 32 == 0 && (shifts[i] != shifts[i + 1]))
                        {
                            shifts.RemoveAt(i);
                            shifts.RemoveAt(i);
                            changed = true;
                        }
                    }
                } while (changed);
                if (shifts.Count() < polymerLength)
                {
                    lock (varSafe) polymerLength = shifts.Count();
                }
            });
            return(polymerLength.ToString());
        }
Пример #5
0
        public static void Main(string[] args)
        {
            PuzzleInput h = new PuzzleInput();

            Console.WriteLine("The sum : " + h.GetSum());
            Console.ReadKey();
        }
Пример #6
0
        protected List <Passport> GetValidPassports()
        {
            var cleanedInputs  = new List <string>();
            var validPassports = new List <Passport>();
            var inputToString  = PuzzleInput
                                 .Aggregate((i, j) => i + " " + j)
                                 .Split("  ");

            var validFields = new string[] {
                "byr:",
                "iyr:",
                "eyr:",
                "hgt:",
                "hcl:",
                "ecl:",
                "pid:",
            };

            foreach (var item in inputToString)
            {
                var passport = new Passport(item, validFields);
                if (passport.isValid())
                {
                    validPassports.Add(passport);
                }
            }

            return(validPassports);
        }
Пример #7
0
        public override async Task Part1()
        {
            var puzzleinput1 = PuzzleInput.Split("\r\n");

            Reactions = puzzleinput1.Select(x => new Reaction(x.Split("=>"))).ToList();


            var fuelReaction = Reactions.Where(x => x.FuelMaterial() != null).FirstOrDefault();

            var foundOre = false;


            var tree      = RecursiveFunction(fuelReaction);
            var reactions = new List <Reaction>();
            var flatlist  = Traverse(tree);

            var inputDic           = new Dictionary <string, int>();
            var flatlistWithoutORE = flatlist.Where(x => x.InputMaterials.FirstOrDefault().Type != "ORE").ToList();
            var flatlistORE        = flatlist.Where(x => x.InputMaterials.FirstOrDefault().Type == "ORE").Distinct().ToList();;


            foreach (var item in flatlistWithoutORE)
            {
                var output        = item.OutputMaterials.FirstOrDefault();
                var inputMaterial = item.InputMaterials;
                int amount;
                var amountNeededAlready = inputDic.TryGetValue(output.Type, out amount);
                if (amount == 0)
                {
                    amount = 1;
                }
                amount = output.Quantity * amount;
                foreach (var input in inputMaterial)
                {
                    for (int i = 0; i < amount; i++)
                    {
                        if (!inputDic.TryAdd(input.Type, input.Quantity))
                        {
                            inputDic[input.Type] += input.Quantity;
                        }
                    }
                }
            }

            var totalOREAmount = 0d;

            foreach (var oreReaction in flatlistORE)
            {
                var output           = oreReaction.OutputMaterials.FirstOrDefault();
                var type             = output.Type;
                var howmanyIsNeeded  = inputDic[type];
                var reactionMultiply = Math.Ceiling((double)howmanyIsNeeded / (double)output.Quantity);

                var inputOre = oreReaction.InputMaterials.FirstOrDefault();
                totalOREAmount += inputOre.Quantity * reactionMultiply;
            }
            var outputs = flatlistWithoutORE.Select(x => x.OutputMaterials);

            ResultPart1 = totalOREAmount.ToString();
        }
Пример #8
0
        public override string Part2()
        {
            var boxIDs = PuzzleInput.Split(new[] { "\r\n" }, StringSplitOptions.None).Select(c => c.ToCharArray()).ToHashSet();
            var numberOfMatchingChars = boxIDs.First().Count() - 1;

            var returnstring = string.Empty;

            Parallel.ForEach(boxIDs, (box, loopState) => Parallel.ForEach(boxIDs, (matchBox, loopState2) =>
            {
                var boxIDBuilder = new StringBuilder();
                if (matchBox != box)
                {
                    for (int i = 0; i < box.Length; i++)
                    {
                        if (box[i] == matchBox[i])
                        {
                            boxIDBuilder.Append(box[i]);
                        }
                    }
                    if (boxIDBuilder.Length == numberOfMatchingChars)
                    {
                        lock (lockLoop)
                        {
                            returnstring = boxIDBuilder.ToString();
                            loopState.Stop();
                            loopState2.Stop();
                        }
                    }
                }
                boxIDBuilder.Clear();
            }));
            return(returnstring);
        }
Пример #9
0
        public override async Task Part1()
        {
            var removegtstSigns = PuzzleInput.Replace("<", "").Replace(">", "");
            var lines           = removegtstSigns.Split("\r\n").Select(x => x.Split(',').Select(y => new string(y.Trim().SkipWhile(z => z == '=').ToArray()))).Select(x => x.Select(y => y.Substring(y.IndexOf('=') + 1).Trim()));;
            var moonsLijst      = lines.Select(x => new Moon(Convert.ToInt32(x.First()), Convert.ToInt32(x.Skip(1).First()), Convert.ToInt32(x.Last())));
            var moons           = moonsLijst.ToList();


            for (int count = 0; count < 1000; count++)
            {
                for (int i = 0; i < moons.Count(); i++)
                {
                    var moon     = moons[i];
                    var allMoons = moons.Where(x => x != moon);
                    moon.DetermineAndSaveVelocity(new Coordinate(allMoons.Count(x => x.Coordinate.X > moon.Coordinate.X) - allMoons.Count(x => x.Coordinate.X < moon.Coordinate.X), allMoons.Count(x => x.Coordinate.Y > moon.Coordinate.Y) - allMoons.Count(x => x.Coordinate.Y < moon.Coordinate.Y), allMoons.Count(x => x.Coordinate.Z > moon.Coordinate.Z) - allMoons.Count(x => x.Coordinate.Z < moon.Coordinate.Z)));
                }

                foreach (var moon in moons)
                {
                    moon.ApplyVelocity();
                }
            }

            var totalEnergy = moons.Select(x => x.GetEnergy()).Sum();

            ResultPart1 = string.Empty;
        }
        private static void Main(string[] args)
        {
            var result1 = Puzzle02.CountValidPolicy1Passwords(PuzzleInput.ToPuzzle2Input());
            var result2 = Puzzle02.CountValidPolicy2Passwords(PuzzleInput.ToPuzzle2Input());

            Console.WriteLine($"Valid passwords (policy 1): {result1}");
            Console.WriteLine($"Valid passwords (policy 2): {result2}");
        }
Пример #11
0
        public void SolvePartTwo()
        {
            Console.WriteLine("Part two:");
            var sum = GetSumEveryone(PuzzleInput.FetchStringArrayRaw(6));

            Console.WriteLine($"Answer is: {sum}");
            Console.WriteLine();
        }
Пример #12
0
        private static void Main(string[] args)
        {
            var result1 = Puzzle06.CountTask1(PuzzleInput.ToPuzzle6Input());
            var result2 = Puzzle06.CountTask2(PuzzleInput.ToPuzzle6Input());

            Console.WriteLine($"Count task 1: {result1}");
            Console.WriteLine($"Count task 2: {result2}");
        }
Пример #13
0
 public Day1(int day) : base(day)
 {
     Title         = "The Tyranny of the Rocket Equation";
     PuzzleInput   = !string.IsNullOrEmpty(TestInput) ? TestInput : Resources.Day1;
     Day1Modules   = PuzzleInput.Split('\n').Select(x => Convert.ToDouble(x));
     SolutionPart1 = "3325342";
     SolutionPart2 = "4985158";
 }
Пример #14
0
        private static void Main(string[] args)
        {
            var result1 = Puzzle04.CountValidPassportsTask1(PuzzleInput.ToPuzzle4Input());
            var result2 = Puzzle04.CountValidPassportsTask2(PuzzleInput.ToPuzzle4Input());

            Console.WriteLine($"Passports valid (task 1): {result1}");
            Console.WriteLine($"Passports valid (task 2): {result2}");
        }
Пример #15
0
        public void SolvePartTwo()
        {
            Console.WriteLine("Part two:");
            var containedBags = this.GetContainedBags(PuzzleInput.FetchStringArray(7));

            Console.WriteLine($"Answer is: {containedBags}");
            Console.WriteLine();
        }
Пример #16
0
        public void SolvePartOne()
        {
            Console.WriteLine("Part one:");
            var numberOfBags = this.GetNumberOfBags(PuzzleInput.FetchStringArray(7));

            Console.WriteLine($"Answer is: {numberOfBags}");
            Console.WriteLine();
        }
Пример #17
0
        public void SolvePartTwo()
        {
            Console.WriteLine("Part two:");
            var trees = Solve2(PuzzleInput.FetchGrid(3));

            Console.WriteLine($"Answer is: {trees}");
            Console.WriteLine();
        }
Пример #18
0
        public void SolvePartTwo()
        {
            Console.WriteLine("Part two:");
            var seatId = GetSeadId(PuzzleInput.FetchStringArray(5));

            Console.WriteLine($"Answer is: {seatId}");
            Console.WriteLine();
        }
Пример #19
0
        public void SolvePartTwo()
        {
            Console.WriteLine("Part two:");
            var gameConsole = new GameConsole(PuzzleInput.FetchStringArray(8));

            Console.WriteLine($"Answer is: {this.TryFixingIt(gameConsole)}");
            Console.WriteLine();
        }
Пример #20
0
        public void SolvePartOne()
        {
            Console.WriteLine("Part one:");
            var trees = Solve(PuzzleInput.FetchGrid(3), 3, 1);

            Console.WriteLine($"Answer is: {trees}");
            Console.WriteLine();
        }
Пример #21
0
        public void SolvePartTwo()
        {
            Console.WriteLine("Part two:");
            var validPassports = CountValidPassports2(PuzzleInput.FetchStringArrayRaw(4));

            Console.WriteLine($"Answer is: {validPassports}");
            Console.WriteLine();
        }
Пример #22
0
 public Day2(int day) : base(day)
 {
     Title          = "1202 Program Alarm";
     PuzzleInput    = !string.IsNullOrEmpty(TestInput) ? TestInput : Resources.Day2;
     ComputerMemory = PuzzleInput.Split(',').Select(x => Convert.ToInt32(x)).ToList();
     SolutionPart1  = "4484226";
     SolutionPart2  = "5696";
 }
Пример #23
0
        public void SolvePartOne()
        {
            Console.WriteLine("Part one:");
            var console = new GameConsole(PuzzleInput.FetchStringArray(8));

            Console.WriteLine($"Answer is: {this.GetAccumulatorAtRepeat(console)}");
            Console.WriteLine();
        }
Пример #24
0
 public Day9(int day) : base(day)
 {
     Title               = "Sensor Boost";
     PuzzleInput         = !string.IsNullOrEmpty(TestInput) ? TestInput : Resources.Day9;
     ComputerMemoryInput = PuzzleInput.Split(',').Select(x => Convert.ToInt64(x)).ToList();
     SolutionPart1       = "3497884671";
     SolutionPart2       = "46470";
 }
        private static void Main(string[] args)
        {
            var result1 = Puzzle05.MaxSeatId(PuzzleInput.ToPuzzle5Input());
            var result2 = Puzzle05.FindSantasSeatId(PuzzleInput.ToPuzzle5Input());

            Console.WriteLine($"Max seat ID (task 1): {result1}");
            Console.WriteLine($"Santa's seat ID (task 2): {result2}");
        }
Пример #26
0
        private long InvestigatePattern(Register register, long instructionPointer, bool startPrint = false)
        {
            InitializeOpcodeList();
            var puzzleLines   = PuzzleInput.Split("\r\n");
            var boundRegister = Convert.ToInt32(puzzleLines.First().Replace("#ip ", ""));


            var samples = new List <Sample>();

            foreach (var puzzleLine in puzzleLines.Skip(1))
            {
                var instructions = puzzleLine.Split(" ");
                var opcode       = GetOpcodeByName(instructions[0]);
                samples.Add(new Sample()
                {
                    Instruction = new Instruction(opcode, instructions[1], instructions[2], instructions[3])
                });
            }

            var reg0       = (long)0;
            var difference = (long)0;

            for (int i = (int)instructionPointer; i < samples.Count(); i++)
            {
                samples[i].Before = register;
                samples[i].Before.Registers[boundRegister] = instructionPointer;
                samples[i].Instruction.Opcode(samples[i]);
                register           = samples[i].After;
                difference         = register.Registers[boundRegister] - instructionPointer;
                instructionPointer = register.Registers[boundRegister];

                Print(i, samples[i], (int)instructionPointer);
                // if ((int)instructionPointer > 10) Print(samples[i], (int)instructionPointer);
                //if (startPrint) Print(i, samples[i], (int)instructionPointer);
                //reg0 = register.Registers[0];
                //if (instructionPointer == 14)
                //{
                //    Print(i, samples[i], (int)instructionPointer);
                //    startPrint = true;
                //}
                //if (instructionPointer == 33)
                //{
                //    startPrint = true;
                //    Print(samples[i], (int)instructionPointer);
                //}

                instructionPointer++;

                if (instructionPointer >= samples.Count())
                {
                    reg0 = samples[i].After.Registers[0];
                    break;
                }
                i = i + (int)difference;
            }

            return(reg0);
        }
Пример #27
0
 public Day4(int day) : base(day)
 {
     Title = "Secure Container";
     //TestInput = "112233-670283"; //152085-670283
     PuzzleInput   = !string.IsNullOrEmpty(TestInput) ? TestInput : Resources.Day4;
     Day2Integers  = PuzzleInput.Split(',').Cast <int>();
     SolutionPart1 = "";
     SolutionPart2 = "";
 }
Пример #28
0
 public Day13(int day) : base(day)
 {
     Title               = "Care Package";
     TestInput           = "";
     PuzzleInput         = !string.IsNullOrEmpty(TestInput) ? TestInput : Resources.Day13;
     ComputerMemoryInput = PuzzleInput.Split(',').Select(x => Convert.ToInt64(x)).ToList();
     SolutionPart1       = "412";
     SolutionPart2       = "20940";
 }
Пример #29
0
        public override string Part1()
        {
            //var testString = @"18 units each with 729 hit points (weak to fire; immune to cold, slashing) with an attack that does 8 radiation damage at initiative 10";
            var game       = new Game();
            var digitRegex = new Regex(@"-?\d+");

            var puzzleLines = PuzzleInput.Split(new[] { "\r\n" }, StringSplitOptions.None);

            string type = string.Empty;
            var    id   = 0;

            foreach (var line in puzzleLines)
            {
                if (line.Length > 0 && line.Length < 50)
                {
                    type = line;
                }
                else if (line.Length == 0)
                {
                    //do nothing
                }
                else
                {
                    var unitGroup = new UnitGroup(++id, type, line, 0);
                    game.UnitGroups.Add(unitGroup);
                }
            }

            while (!game.GameOver)
            {
                game.UnitGroups.ForEach((c) => { c.UnitToAttack = null; c.UnitToDefend = null; });
                //Choosing Phase

                var unitList = game.UnitGroups.OrderByDescending(c => c.EffectivePower()).ThenByDescending(c => c.Initiative).ToList();
                for (int i = 0; i < unitList.Count(); i++)
                {
                    var unit = game.UnitGroups.First(c => c.ID == unitList[i].ID);
                    if (!unit.GameOver())
                    {
                        unit.ChooseTarget(game.UnitGroups);
                    }
                }

                var attackUnitList = game.UnitGroups.OrderByDescending(c => c.Initiative).ToList();
                for (int i = 0; i < attackUnitList.Count(); i++)
                {
                    var unit = game.UnitGroups.First(c => c.ID == attackUnitList[i].ID);
                    if (!unit.GameOver())
                    {
                        unit.Attack();
                    }
                }
                game.UnitGroups.RemoveAll(c => c.GameOver());
                //Print(game.UnitGroups);
            }
            return(game.Part1());
        }
Пример #30
0
 public Day99(int day) : base(day)
 {
     Title         = "";
     TestInput     = "";
     PuzzleInput   = !string.IsNullOrEmpty(TestInput) ? TestInput : Resources.Day1;
     Day2Integers  = PuzzleInput.Split(',').Cast <int>();
     SolutionPart1 = "";
     SolutionPart2 = "";
 }