Пример #1
0
        public static int FirstPart(string filename)
        {
            List <Passport> validPassports = new List <Passport>();

            var lines = ReadInputs.ReadWholeFileAsString(filename).Split(LINESEPARATOR + LINESEPARATOR).Select(l => l.Trim()).ToList();
            int count = 0;

            foreach (var line in lines)
            {
                var passport = new Passport(line, LINESEPARATOR);

                if (passport.IsValid())
                {
                    validPassports.Add(passport);
                    count++;
                }
            }

            //var birthYears = validPassports.Select(p => p.BirthYear).ToList();
            //var issueYears = validPassports.Select(p => p.IssueYear).ToList();
            //var expirationYears = validPassports.Select(p => p.ExpirationYear).ToList();
            //var heights = validPassports.Select(p => p.Height).ToList();
            //var haircolors = validPassports.Select(p => p.HairColor).ToList();
            //var eyecolors = validPassports.Select(p => p.EyeColor).ToList();
            //var passportIds = validPassports.Select(p => p.PassportId).ToList();

            return(count);
        }
Пример #2
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]);
        }
Пример #3
0
        static Object PartB()
        {
            List <string>          input = ReadInputs.ReadStrings(inputPath);
            int                    ans   = 0;
            Dictionary <char, int> dict  = new Dictionary <char, int>();
            int                    n     = 0;

            foreach (string s in input)
            {
                if (s == "")
                {
                    ans += dict.Where(x => x.Value == n).Count();
                    dict = new Dictionary <char, int>();
                    n    = 0;
                }
                else
                {
                    foreach (char c in s)
                    {
                        if (!dict.ContainsKey(c))
                        {
                            dict[c] = 0;
                        }
                        dict[c]++;
                    }
                    n++;
                }
            }
            Console.WriteLine("Part B: Result is {0}", ans);
            return(ans);
        }
Пример #4
0
        static Object PartB()
        {
            List <long> input = ReadInputs.ReadLongs(inputPath);

            input.Sort();
            long ans = 0;

            for (int i = 0; i < input.Count; i++)
            {
                for (int j = 0; j < input.Count; j++)
                {
                    if (j != i)
                    {
                        long a = input[i];
                        long b = input[j];
                        long c = 2020 - a - b;
                        if (input.Contains(c))
                        {
                            ans = a * b * c;
                            break;
                        }
                    }
                }
            }
            Console.WriteLine("Part B: Result is {0}", ans);
            return(ans);
        }
Пример #5
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));
        }
Пример #6
0
        /// <summary>
        /// How many passwords are valid based on a given rule.
        /// Rule is in format 1-3 a: pass where 1 is the minimum number of ocurrences of a, 3 is maximum number of occurences of a, a is a varible and pass is a string
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static int FirstPart(string filename)
        {
            var    reader = ReadInputs.OpenInputFile(filename);
            string line;
            int    numOfValidPasswords = 0;
            int    row = 0;

            while ((line = reader.ReadLine()) != null)
            {
                var passwordRule = new PasswordRule(line);

                // Uncomment for first part
                //var isValidOld = passwordRule.IsValidOldPolicy();
                //if (isValidOld)
                //{
                //    numOfValidPasswords++;
                //}

                // Uncomment for 2nd part
                var isValidNew = passwordRule.IsValidNewPolicy();
                if (isValidNew)
                {
                    numOfValidPasswords++;
                }

                Console.WriteLine(String.Format("Row {0}, Rule: {1}, IsValid: {2}", row, passwordRule.ToString(), isValidNew));
            }

            reader.Close();

            return(numOfValidPasswords);
        }
Пример #7
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");
        }
Пример #8
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");
        }
Пример #9
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));
        }
Пример #10
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);
        }
Пример #11
0
        static Object PartA()
        {
            List <int> input = ReadInputs.ReadInts(inputPath);
            int        ans   = 0;

            Console.WriteLine("Part A: Result is {0}", ans);
            return(ans);
        }
Пример #12
0
        static Object PartA()
        {
            List <string> input = ReadInputs.ReadStrings(inputPath);
            HashSet <int> ids   = GetIds(input);
            int           ans   = ids.Max();

            Console.WriteLine("Part A: Result is {0}", ans);
            return(ans);
        }
Пример #13
0
        static Object PartB()
        {
            List <string> input = ReadInputs.ReadStrings(inputPath);
            HashSet <int> ids   = GetIds(input);
            int           ans   = ids.Where(x => !ids.Contains(x + 1) && ids.Contains(x + 2)).Min() + 1;

            Console.WriteLine("Part B: Result is {0}", ans);
            return(ans);
        }
Пример #14
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);
        }
Пример #15
0
        public static int FirstPart(string filename)
        {
            var  lines = ReadInputs.ReadAllStrings(ReadInputs.GetFullPath(filename));
            int  sum;
            bool isInfiniteLoop;

            (isInfiniteLoop, sum) = WhileLoop(lines);

            return(sum);
        }
Пример #16
0
        static Object PartB()
        {
            List <string> input = ReadInputs.ReadStrings(inputPath);
            int           a     = 0;
            long          ans   = calcTrees(input, 1, 1);

            ans *= calcTrees(input, 1, 3);
            ans *= calcTrees(input, 1, 5);
            ans *= calcTrees(input, 1, 7);
            ans *= calcTrees(input, 2, 1);
            Console.WriteLine("Part B: Result is {0}", ans);
            return(ans);
        }
Пример #17
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);
        }
Пример #18
0
        static Object PartA()
        {
            List <string> input = ReadInputs.ReadStrings(inputPath);
            int           ans   = 0;
            int           c     = 0;

            for (int r = 0; r < input.Count; r++)
            {
                if (input[r][c % input[0].Count()] == '#')
                {
                    ans++;
                }
                c += 3;
            }
            Console.WriteLine("Part A: Result is {0}", ans);
            return(ans);
        }
Пример #19
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!");
        }
Пример #20
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);
        }
Пример #21
0
        static Object PartA()
        {
            List <int> input = ReadInputs.ReadInts(inputPath);

            input.Sort();
            int ans = 0;

            foreach (int a in input)
            {
                int b = 2020 - a;
                if (input.Contains(b))
                {
                    ans = a * b;
                    break;
                }
            }
            Console.WriteLine("Part A: Result is {0}", ans);
            return(ans);
        }
Пример #22
0
        static Object PartA()
        {
            List <string>  input = ReadInputs.ReadStrings(inputPath);
            int            ans   = 0;
            HashSet <char> set   = new HashSet <char>();

            foreach (string s in input)
            {
                if (s == "")
                {
                    ans += set.Count;
                    set  = new HashSet <char>();
                }
                else
                {
                    set.UnionWith(s.ToHashSet());
                }
            }
            ans += set.Count;
            Console.WriteLine("Part A: Result is {0}", ans);
            return(ans);
        }
Пример #23
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);
        }
Пример #24
0
        /// <summary>
        /// Method to be run to ge the 2nd part of the solution.
        /// Find three numbers in list that give a sum of 2020
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static int SecondPart(string filename)
        {
            var numbers = ReadInputs.ReadAllInts(filename);

            for (int i = 0; i < numbers.Count; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    if (numbers[i] + numbers[j] > 2020)
                    {
                        continue;                                                   // if two numbers are greater than 2020, no sense trying out the 3rd.
                    }
                    for (int k = 0; k < j; k++)
                    {
                        if (numbers[i] + numbers[j] + numbers[k] == 2020)
                        {
                            return(numbers[i] * numbers[j] * numbers[k]);
                        }
                    }
                }
            }

            throw new Exception("No sequence found.");
        }
Пример #25
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);
        }
Пример #26
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);
        }
Пример #27
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));
        }
Пример #28
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));
        }
Пример #29
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));
        }