Пример #1
0
        public static int FirstPart(string filename)
        {
            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            var rows  = lines.Count;
            var cols  = lines[0].Length;

            char[,] matrix     = new char[rows, cols];
            char[,] nextMatrix = new char[rows, cols];
            for (var i = 0; i < lines.Count; i++)
            {
                var currArray = lines[i].ToCharArray();
                for (var j = 0; j < currArray.Length; j++)
                {
                    matrix[i, j] = currArray[j];
                }
            }

            int numOfChanges = -1;

            while (numOfChanges != 0)
            {
                // PrintMatrix(matrix, rows, cols);

                nextMatrix = (char[, ])matrix.Clone();

                numOfChanges = ApplyRulesForPartTwo(matrix, nextMatrix, rows, cols);

                matrix = (char[, ])nextMatrix.Clone();
            }

            return(CountPlaces(matrix, rows, cols));
        }
Пример #2
0
        public static long FirstPart(string filename)
        {
            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            Dictionary <long, long> memory = new Dictionary <long, long>();
            string currentMask             = string.Empty;

            List <long> addresses = new List <long>();

            foreach (var line in lines)
            {
                if (line.StartsWith("mask = "))
                {
                    currentMask = line.Substring("mask = ".Length);
                }
                else
                {
                    var  parts = line.Split("] = ");
                    long value = Convert.ToInt64(parts[1]);

                    // Task 1:
                    // addresses = new List<long>() { Convert.ToInt64(parts[0].Substring(4)) };

                    // Task 2:
                    addresses = GetPossibleAddresses(Convert.ToInt64(parts[0].Substring(4)), currentMask);

                    foreach (var address in addresses)
                    {
                        // Task 1
                        // var newValue = MaskValue(value, currentMask);

                        // Task 2
                        var newValue = value;

                        if (!memory.ContainsKey(address))
                        {
                            memory.Add(address, newValue);
                        }
                        else
                        {
                            memory[address] = newValue;
                        }

                        Console.WriteLine("Writing " + newValue + " to memory address " + address);
                    }
                }
            }

            long sum = 0;

            foreach (var item in memory)
            {
                sum += item.Value;
            }

            return(sum);
        }
Пример #3
0
        public static int FirstPart(string filename)
        {
            var  lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int  sum;
            bool isInfiniteLoop;

            (isInfiniteLoop, sum) = WhileLoop(lines);

            return(sum);
        }
Пример #4
0
        public static long FirstPart(string filename)
        {
            List <TobogganPath> paths = new List <TobogganPath>()
            {
                new TobogganPath(1, 1),
                new TobogganPath(1, 3),
                new TobogganPath(1, 5),
                new TobogganPath(1, 7),
                new TobogganPath(2, 1)
            };

            int  width;
            long product = 1;

            var data = ReadInputs.ReadAllStrings(filename);

            foreach (var path in paths)
            {
                for (var i = path.RowParam; i < data.Count; i += path.RowParam)
                {
                    string line = data[i];
                    width   = line.Length;
                    path.Y += path.RowParam;
                    path.X += path.ColParam;

                    if (line.Substring((path.X) % width, 1) == "#")
                    {
                        path.NumberOfTrees++;
                        line = line.Substring(0, ((path.X) % width)) + "X" + line.Substring(((path.X) % width) + 1);
                    }
                    else
                    {
                        line = line.Substring(0, ((path.X) % width)) + "O" + line.Substring(((path.X) % width) + 1);
                    }

                    Console.WriteLine("{0} ---> {1} {2}", line, path.X, path.Y);

                    // Console.WriteLine("{0}, with {1} at position {2} (len: {3})", line, line.Substring((path.X) % width, 1), (path.X) % width, width);
                }
                Console.WriteLine("Path {0} {1} --> Number = {2} \n\n\n", path.ColParam, path.RowParam, path.NumberOfTrees);

                product *= path.NumberOfTrees;
            }



            return(product);
        }
Пример #5
0
        public static int SecondPart(string filename)
        {
            var  lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int  sum;
            bool isInfiniteLoop;

            for (var i = 0; i < lines.Count; i++)
            {
                if (lines[i].IndexOf("jmp") != -1)
                {
                    // Replace jmp with nop
                    lines[i] = lines[i].Replace("jmp", "nop");

                    // Run the loop
                    (isInfiniteLoop, sum) = WhileLoop(lines);

                    // Check for conditions
                    if (!isInfiniteLoop)
                    {
                        return(sum);
                    }

                    // Replace back
                    lines[i] = lines[i].Replace("nop", "jmp");
                }
                else if (lines[i].IndexOf("nop") != -1)
                {
                    // Replace jmp with nop
                    lines[i] = lines[i].Replace("nop", "jmp");

                    // Run the loop
                    (isInfiniteLoop, sum) = WhileLoop(lines);

                    // Check for conditions
                    if (!isInfiniteLoop)
                    {
                        return(sum);
                    }

                    // Replace back
                    lines[i] = lines[i].Replace("jmp", "nop");
                }
            }

            throw new Exception("We should never end up here!");
        }
Пример #6
0
        public static int FirstPart(string filename)
        {
            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int count = 0;

            // Task 1
            //Dictionary<string, Node> nodes = GetTreeByChild(lines);
            //List<string> countedColors = new List<string>();
            //count = CountForChildNode("shiny gold", nodes,countedColors) - 1;    // The minus one is to remove yourself

            // Task 2
            Dictionary <string, Node> nodes = GetTreeByParent(lines);

            count = SumForParentNode("shiny gold", nodes) - 1;                      // The minus one is to remove yourself


            return(count);
        }
Пример #7
0
        /// <summary>
        /// Task 5 - find the seat with the highest ID
        /// </summary>
        public static int FirstPart(string filename)
        {
            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int max   = 0;

            var seats = new bool[817];

            foreach (var line in lines)
            {
                var rowBin = line.Substring(0, 7).Replace("F", "0").Replace("B", "1");
                var colBin = line.Substring(7).Replace("R", "1").Replace("L", "0");

                int row = Convert.ToInt32(rowBin, 2);
                int col = Convert.ToInt32(colBin, 2);

                int seatId = row * 8 + col;
                seats[seatId] = true;

                if (seatId > max)
                {
                    max = seatId;
                }
            }

            // 1st part solution
            // return max;

            for (var i = 1; i < seats.Length - 1; i++)
            {
                if (seats[i] == false && seats[i - 1] && seats[i + 1])
                {
                    return(i);
                }
            }

            return(-1);
        }
Пример #8
0
        public static int SecondPart(string filename)
        {
            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));

            int initialWidth  = lines[0].Length;
            int initialHeight = lines.Count;
            int n             = 6; // number of steps to play

            // Define matrixes.
            // Max possibility of expanding is n in each direction => 2 n + initial dimension!
            var maxWidth  = initialWidth + (2 * n);
            var maxHeight = initialHeight + (2 * n);
            var maxDepth  = (2 * n) + 1;
            var maxTime   = (2 * n) + 1;

            char[,,,] matrix     = new char[maxWidth, maxHeight, maxDepth, maxTime];
            char[,,,] nextMatrix = new char[maxWidth, maxHeight, maxDepth, maxTime];

            // Initialize matrixes from lines
            for (int i = 0; i < maxWidth; i++)
            {
                for (int j = 0; j < maxHeight; j++)
                {
                    for (int k = 0; k < maxDepth; k++)
                    {
                        for (int l = 0; l < maxTime; l++)
                        {
                            matrix[i, j, k, l]     = INACTIVE;
                            nextMatrix[i, j, k, l] = INACTIVE;
                        }
                    }
                }
            }


            for (int i = 0; i < lines.Count; i++)
            {
                for (int j = 0; j < lines[0].Length; j++)
                {
                    var tempChars = lines[i].Substring(j, 1).ToCharArray();
                    matrix[n + j, n + i, n, n]     = tempChars[0];
                    nextMatrix[n + j, n + i, n, n] = tempChars[0];
                }
            }


            // Do the loop
            int currentStep = 0;

            while (currentStep < n)
            {
                currentStep++;

                // Define initial coordinates and widths
                var currentX     = n - currentStep;
                var currentWidth = initialWidth + (2 * currentStep);

                var currentY      = n - currentStep;
                var currentHeight = initialHeight + (2 * currentStep);

                var currentZ     = n - currentStep;
                var currentDepth = 1 + 2 * currentStep;

                var currentT    = n - currentStep;
                var currentTime = 1 + 2 * currentStep;

                Console.WriteLine("Current count = " + CountActives(matrix, maxWidth, maxHeight, maxDepth, maxTime));
                //PrintMatrix(matrix, currentX, currentY, currentZ, currentT, currentWidth, currentHeight, currentDepth, currentTime);

                // Check required space
                for (int i = 0; i < currentWidth; i++)
                {
                    for (int j = 0; j < currentHeight; j++)
                    {
                        for (int k = 0; k < currentDepth; k++)
                        {
                            for (int l = 0; l < currentTime; l++)
                            {
                                // Modify nextMatrix based on matrix
                                ModifyNextMatrix(currentX + i, currentY + j, currentZ + k, currentT + l, matrix, nextMatrix, maxWidth, maxHeight, maxDepth, maxTime);
                            }
                        }
                    }
                }


                matrix = (char[, , , ])nextMatrix.Clone();
            }


            return(CountActives(matrix, maxWidth, maxHeight, maxDepth, maxTime));
        }
Пример #9
0
        public static long FirstPart(string filename)
        {
            var lines     = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int timestamp = Convert.ToInt32(lines[0]);
            var busses    = lines[1].Split(",").Select(l => l.Trim() == "x" ? -1 : Convert.ToInt32(l)).ToList();

            int bestBus      = -1;
            int shortestTime = busses[busses.Count - 1] + 1;


            // TASK 1:
            //foreach (var bus in busses)
            //{
            //    if (bus != -1)
            //    {
            //        var minutesSinceLastLeft = timestamp % bus;
            //        if (minutesSinceLastLeft == 0)
            //        {
            //            bestBus = bus;
            //            shortestTime = 0;
            //            break;
            //        }
            //        else
            //        {
            //            // last bus of this ID left minutesSinceLastLeft ago.
            //            // Next one is coming in bus - minutessincelastleft
            //            if (bus - minutesSinceLastLeft < shortestTime)
            //            {
            //                bestBus = bus;
            //                shortestTime = bus - minutesSinceLastLeft;
            //            }
            //        }
            //    }
            //}

            //return bestBus * shortestTime;


            // TASK 2:
            long i    = 0;
            long step = busses[0];
            List <KeyValuePair <long, int> > onlyBusses = busses.Where(b => b != -1).Select(b => new KeyValuePair <long, int>(b, busses.IndexOf(b))).ToList();

            bool isFinished       = false;
            int  indexOfBus       = 1;
            var  nextBusToCompare = onlyBusses[indexOfBus].Key;
            long orderOfMagnitude = 1;

            while (!isFinished)
            {
                if (i / orderOfMagnitude >= 1)
                {
                    Console.WriteLine("New order of magnitude, i = " + i + "(" + Math.Log10(orderOfMagnitude) + "), step = " + step);
                    orderOfMagnitude *= 10;
                }

                // Console.WriteLine("Checking for i=" + i);
                // Check if other busses come "in their place"
                var nextBusIn = WhenNextBusComes(i, nextBusToCompare);
                if (nextBusIn == onlyBusses[indexOfBus].Value % onlyBusses[indexOfBus].Key)
                {
                    // Works for next bus.
                    // Increase step, increase indexOfBus
                    step *= nextBusToCompare;
                    indexOfBus++;
                    if (indexOfBus == onlyBusses.Count())
                    {
                        break;
                    }
                    nextBusToCompare = onlyBusses[indexOfBus].Key;
                    Console.WriteLine("Now comparing to bus " + nextBusToCompare + " with new step being " + step);
                }
                else
                {
                    i += step;
                }
            }

            return(i);
        }
Пример #10
0
        public static int FirstPart(string filename)
        {
            int x = 0, y = 0;
            int direction = 90;

            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));

            foreach (var line in lines)
            {
                char command = Convert.ToChar(line.Substring(0, 1));
                int  arg     = Convert.ToInt32(line.Substring(1));

                Console.Write("After command " + line);

                if (command == 'F')
                {
                    if (direction == 0)
                    {
                        command = 'N';
                    }
                    else if (direction == 90)
                    {
                        command = 'E';
                    }
                    else if (direction == 180)
                    {
                        command = 'S';
                    }
                    else if (direction == 270)
                    {
                        command = 'W';
                    }
                    else
                    {
                        throw new Exception("Jebo te Pitagora da te jebo!");
                    }
                }

                switch (command)
                {
                case 'N':
                    y = y + arg;
                    break;

                case 'S':
                    y = y - arg;
                    break;

                case 'E':
                    x = x - arg;
                    break;

                case 'W':
                    x = x + arg;
                    break;

                case 'L':
                    direction = (direction - arg) % 360;
                    if (direction < 0)
                    {
                        direction += 360;
                    }
                    break;

                case 'R':
                    direction = (direction + arg) % 360;
                    break;

                default:
                    throw new Exception("We should never hit here!");
                    break;
                }

                Console.WriteLine(" we are at " + x + "," + y + " heading " + direction + ".");
            }


            return(Math.Abs(x) + Math.Abs(y));
        }
Пример #11
0
        public static int SecondPart(string filename)
        {
            int x = 0, y = 0;
            int waypointX = 10, waypointY = 1;

            var lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));

            foreach (var line in lines)
            {
                char command = Convert.ToChar(line.Substring(0, 1));
                int  arg     = Convert.ToInt32(line.Substring(1));

                if (command == 'L')
                {
                    command = 'R';
                    arg     = (360 - arg) % 360;
                }

                Console.Write("After command " + line);

                switch (command)
                {
                case 'N':
                    waypointY += arg;
                    break;

                case 'S':
                    waypointY -= arg;
                    break;

                case 'E':
                    waypointX += arg;
                    break;

                case 'W':
                    waypointX -= arg;
                    break;

                case 'R':
                    int temp;
                    switch (arg)
                    {
                    case 0:
                        break;

                    case 90:
                        temp      = waypointX;
                        waypointX = waypointY;
                        waypointY = -temp;
                        break;

                    case 180:
                        waypointY = -waypointY;
                        waypointX = -waypointX;
                        break;

                    case 270:
                        temp      = waypointX;
                        waypointX = -waypointY;
                        waypointY = temp;
                        break;

                    default:
                        throw new Exception("Jebo te Pitagora da te jebo!");
                        break;
                    }
                    break;

                case 'F':
                    x += arg * waypointX;
                    y += arg * waypointY;
                    break;

                default:
                    throw new Exception("We should never hit here!");
                    break;
                }

                Console.WriteLine(" we are at " + x + "," + y + " with waypoint [" + waypointX + "," + waypointY + "].");
            }


            return(Math.Abs(x) + Math.Abs(y));
        }
Пример #12
0
        public static long FirstPart(string filename)
        {
            var lines        = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int ruleLines    = lines.IndexOf("your ticket:") - 1;
            int otherTickets = lines.IndexOf("nearby tickets:") + 1;

            List <Rule> rules = CreateRules(lines, ruleLines);

            // Dictionary for controlling columns, which rules can be for which column
            Dictionary <int, List <string> > dict = new Dictionary <int, List <string> >();

            for (int i = 0; i < rules.Count; i++)
            {
                dict.Add(i, rules.Select(r => r.Name).ToList());
            }

            List <string> validLines = new List <string>();

            int sum = 0;

            for (int i = otherTickets; i < lines.Count; i++)
            {
                var  parts       = lines[i].Split(',').Select(l => Convert.ToInt32(l)).ToList();
                bool isLineValid = true;
                foreach (var n in parts)
                {
                    bool isValidForRules = false;
                    foreach (var rule in rules)
                    {
                        if (rule.IsValid(n))
                        {
                            isValidForRules = true;
                            break;
                        }
                    }

                    if (!isValidForRules)
                    {
                        sum        += n;
                        isLineValid = false;
                        break;
                    }
                }

                if (isLineValid)
                {
                    validLines.Add(lines[i]);
                }
            }


            for (int i = 0; i < rules.Count; i++)
            {
                for (int j = 0; j < validLines.Count; j++)
                {
                    var parts = validLines[j].Split(',').Select(l => Convert.ToInt32(l)).ToList();

                    foreach (var rule in rules)
                    {
                        if (!rule.IsValid(parts[i]))
                        {
                            dict[i].Remove(rule.Name);
                        }
                    }
                }
            }

            long product       = 1;
            var  myTicketParts = lines[ruleLines + 2].Split(',').Select(l => Convert.ToInt32(l)).ToList();
            KeyValuePair <int, List <string> > kvPair = dict.FirstOrDefault(d => d.Value.Count == 1);

            while (kvPair.Value != null && kvPair.Value.Count > 0)
            {
                // We know for sure that index KEY is field VALUE[0].
                if (kvPair.Value[0].StartsWith("departure"))
                {
                    product *= myTicketParts[kvPair.Key];
                }

                // Remove the condition from all others
                string condition = kvPair.Value[0];
                foreach (var item in dict)
                {
                    item.Value.Remove(condition);
                }

                kvPair = dict.FirstOrDefault(d => d.Value.Count == 1);
            }

            return(product);
        }