コード例 #1
0
        public static int FirstPart(string filename)
        {
            int          sum           = 0;
            const string LINESEPARATOR = "\r\n";
            var          sections      = ReadInputs.ReadWholeFileAsString(ReadInputs.GetFullPath(filename)).Split(LINESEPARATOR + LINESEPARATOR);

            List <char> allYes = new List <char>();

            for (int index = 0; index < sections.Length; index++)
            {
                var section = sections[index];


                // PART I
                // List<char> chars = new List<char>();
                //var cleanSection = section.Replace(LINESEPARATOR, "");
                //for (int i = 0; i < cleanSection.Length; i++)
                //{
                //    var currentChar = Convert.ToChar(cleanSection.Substring(i, 1));
                //    if (!chars.Contains(currentChar)) chars.Add(currentChar);
                //}

                //sum += chars.Count;

                // PART II
                // Console.WriteLine("Section: \r\n{0}", section);
                var         lines   = section.Split(LINESEPARATOR).ToList();
                List <char> answers = new List <char>();

                for (var lineNumber = 0; lineNumber < lines.Count; lineNumber++)
                {
                    string line          = lines[lineNumber];
                    var    personAnswers = line.ToCharArray().Distinct().OrderBy(c => c).ToList();
                    if (lineNumber == 0)
                    {
                        answers = personAnswers;
                    }
                    else
                    {
                        Console.WriteLine("Comparing\r\n{0}\r\n{1}", string.Join(' ', answers), string.Join(' ', personAnswers));

                        for (var k = answers.Count - 1; k >= 0; k--)
                        {
                            if (!personAnswers.Contains(answers[k]))
                            {
                                Console.WriteLine("Removing {0}", answers[k]);
                                answers.RemoveAt(k);
                            }
                        }
                    }
                }

                Console.WriteLine("Answers left: {0}", string.Join(' ', answers));
                //Console.ReadKey();

                sum += answers.Count;
            }

            return(sum);
        }
コード例 #2
0
        public static Int64 FirstPart(string filename)
        {
            var lines          = ReadInputs.ReadAllInt64s(ReadInputs.GetFullPath(filename));
            var preambleLength = 25;

            var currentSums = CalculateInitialSums(lines, preambleLength);

            for (var i = preambleLength; i < lines.Count; i++)
            {
                //foreach (var item in currentSums)
                //{
                //    Console.Write(string.Format("{0} ", item));
                //}
                //Console.WriteLine(string.Format("comparing with {0}", lines[i]));

                if (!currentSums.Contains(lines[i]))
                {
                    return(lines[i]);
                }
                else
                {
                    currentSums = RecalculateCurrentSums(currentSums, lines, i, preambleLength);
                }
            }

            throw new Exception("We should never get here");
        }
コード例 #3
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));
        }
コード例 #4
0
        public static Int64 SecondPart(string filename)
        {
            var desiredSum = FirstPart(filename);
            var lines      = ReadInputs.ReadAllInt64s(ReadInputs.GetFullPath(filename));

            for (var i = 0; i < lines.Count; i++)
            {
                Int64 sum = lines[i];
                var   j   = i + 1;
                Int64 min = lines[i];
                Int64 max = lines[i];
                while (sum < desiredSum && j < lines.Count)
                {
                    if (min > lines[j])
                    {
                        min = lines[j];
                    }
                    if (max < lines[j])
                    {
                        max = lines[j];
                    }
                    sum += lines[j];
                    j++;
                }

                if (sum == desiredSum)
                {
                    return(min + max);
                }
            }

            throw new Exception("We should never get here");
        }
コード例 #5
0
        public static Int64 SecondPart(string filename)
        {
            var lines = ReadInputs.ReadAllInt64s(ReadInputs.GetFullPath(filename)).OrderBy(l => l).ToList();
            var max   = lines[lines.Count - 1];

            // lines.Add(max);

            Int64[] numOfSolutions = new Int64[max + 1];

            // Knapsackish algorithm
            for (int i = 0; i < lines.Count; i++)
            {
                Int64 num = lines[i];

                if (num <= 3)
                {
                    numOfSolutions[lines[i]]++;                    // If number < 3 then it can be added initially
                }
                for (var j = lines[i] - 1; j > 0 && j > lines[i] - 4; j--)
                {
                    // Check if there exist previous solutions for numbers lines[j] - 3
                    if (numOfSolutions[j] != 0)
                    {
                        numOfSolutions[lines[i]] += numOfSolutions[j];
                    }
                }
            }

            return(numOfSolutions[numOfSolutions.Length - 1]);
        }
コード例 #6
0
        public static int FirstPart(string filename)
        {
            var lines       = ReadInputs.ReadAllInts(ReadInputs.GetFullPath(filename)).OrderBy(l => l).ToList();
            var numOfOnes   = 0;
            var numOfThrees = 0;

            var currentVoltage = 0;
            var myVoltage      = lines[lines.Count - 1] + 3;

            foreach (var line in lines)
            {
                if (line - currentVoltage == 1)
                {
                    numOfOnes++;
                }
                else if (line - currentVoltage == 3)
                {
                    numOfThrees++;
                }

                currentVoltage = line;
            }

            return(numOfOnes * (numOfThrees + 1));
        }
コード例 #7
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);
        }
コード例 #8
0
        public static int FirstPart(string filename)
        {
            var  lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int  sum;
            bool isInfiniteLoop;

            (isInfiniteLoop, sum) = WhileLoop(lines);

            return(sum);
        }
コード例 #9
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!");
        }
コード例 #10
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);
        }
コード例 #11
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);
        }
コード例 #12
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));
        }
コード例 #13
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);
        }
コード例 #14
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));
        }
コード例 #15
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));
        }
コード例 #16
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);
        }