Exemple #1
0
        public string SolveSecondStar(StreamReader reader)
        {
            var adapters = StreamParsers.GetStreamAsLongIntList(reader);

            // Add port, which has effective joltage 0
            adapters.Add(0);
            adapters.Sort();

            // Build up an array of possibilities, where possibilities[i] represents
            // the number of possible ways to configure a valid adapter chain
            // ending in i
            long[] possibilities = new long[adapters.Max() + 1];

            // Initialize possibilities[0] to 1, because there is only one way
            // to configure the port
            possibilities[0] = 1;
            possibilities[1] = adapters.Contains(1) ? 1 : 0;
            possibilities[2] = possibilities[1] + (adapters.Contains(2) ? 1 : 0);

            for (int i = 3; i < adapters.Count(); i++)
            {
                var adapter = adapters[i];
                possibilities[adapter] += possibilities[adapter - 3];
                possibilities[adapter] += possibilities[adapter - 2];
                possibilities[adapter] += possibilities[adapter - 1];
            }

            return(possibilities.Last().ToString());
        }
Exemple #2
0
        /*
         * For part 2, the input is modified as follows:
         * 0: 8 11 (this is the same)
         * 8: 42 | 42 8
         * 11: 42 31 | 42 11 31
         *
         * When expanding out rule 0, we see the following pattern:
         * 0: 42 [42 [42.. ] ] [42 [42 [42.. ..31] 31] 31]
         *
         * So instead of modifying our grammar solver to handle these infinite cases, we can
         * simply check to see if the string matches:
         *
         * 0: 42 42 42... 31 31...
         * where the number of rule 42 matches is greater than the number of rule 31 matches
         * and the number of rule 31 matches must be at least 1
         */
        public string SolveSecondStar(StreamReader reader)
        {
            var lines = StreamParsers.GetStreamAsStringList(reader);
            var index = BuildRules(lines);

            long count = 0;

            for (int i = index; i < lines.Count; i++)
            {
                var word = lines[i];
                int num42Matches, num31Matches;

                var last42Index = CheckRuleRepeat(word, 42, 0, out num42Matches);
                if (num42Matches < 2)
                {
                    // Start of string needs to match rule 42 at least twice in order to be valid
                    continue;
                }
                var last31Index = CheckRuleRepeat(word, 31, last42Index, out num31Matches);

                // If the rest of the string exactly matched some number of rule 31s and
                // there were more rule 42 matches than rule 31, it is valid according to the
                // new rules definitions
                if (last31Index == word.Length && num31Matches > 0 && num42Matches > num31Matches)
                {
                    count++;
                }
            }

            return(count.ToString());
        }
Exemple #3
0
        public string SolveSecondStar(StreamReader reader)
        {
            var boardingPasses = StreamParsers.GetStreamAsStringList(reader);

            foreach (var pass in boardingPasses)
            {
                var rowEncoding    = pass.Substring(0, 7);
                var columnEncoding = pass.Substring(7);

                var row    = GetRow(rowEncoding);
                var column = GetColumn(columnEncoding);

                var id = row * 8 + column;
                seatsFound.Add(id);
            }

            for (int i = 0; i <= 1024; ++i)
            {
                if (!seatsFound.Contains(i))
                {
                    if (seatsFound.Contains(i - 1) && seatsFound.Contains(i + 1))
                    {
                        return(i.ToString());
                    }
                }
            }

            throw new Exception("Unable to find seat");
        }
Exemple #4
0
        public string SolveFirstStar(StreamReader reader)
        {
            var adapters = StreamParsers.GetStreamAsLongIntList(reader);

            adapters.Sort();

            long currentJoltage = 0;
            int  smallJumps     = 0;
            int  bigJumps       = 0;

            foreach (var adapter in adapters)
            {
                if (adapter - currentJoltage == 1)
                {
                    smallJumps++;
                }
                else
                {
                    bigJumps++;
                }
                currentJoltage = adapter;
            }
            bigJumps++;
            return((smallJumps * bigJumps).ToString());
        }
Exemple #5
0
        public string SolveSecondStar(StreamReader reader)
        {
            treeMap = StreamParsers.GetStreamAs2DIntArray(reader);

            var treeProduct = CountTrees(1, 1) * CountTrees(3, 1) * CountTrees(5, 1) * CountTrees(7, 1) * CountTrees(1, 2);

            return(treeProduct.ToString());
        }
Exemple #6
0
        public string SolveFirstStar(StreamReader reader)
        {
            var lines = StreamParsers.GetStreamAsStringList(reader);

            foreach (var line in lines)
            {
                var split       = line.Split(" (contains ");
                var ingredients = split[0].Split(null);
                var allergens   = split[1].Substring(0, split[1].Length - 1).Split(", ");

                foreach (var allergen in allergens)
                {
                    if (!PossibleIngredients.ContainsKey(allergen))
                    {
                        PossibleIngredients.Add(allergen, new HashSet <string>());
                        foreach (var ingredient in ingredients)
                        {
                            PossibleIngredients[allergen].Add(ingredient);
                        }
                    }
                    else
                    {
                        PossibleIngredients[allergen].IntersectWith(ingredients);
                    }
                }

                foreach (var ingredient in ingredients)
                {
                    if (IngredientCounts.ContainsKey(ingredient))
                    {
                        IngredientCounts[ingredient]++;
                    }
                    else
                    {
                        IngredientCounts[ingredient] = 1;
                    }
                }
            }

            var allIngredients = new HashSet <string>(IngredientCounts.Keys);

            foreach (var allergen in PossibleIngredients.Keys)
            {
                foreach (var ingredient in PossibleIngredients[allergen])
                {
                    allIngredients.Remove(ingredient);
                }
            }

            int count = 0;

            foreach (var ingredient in allIngredients)
            {
                count += IngredientCounts[ingredient];
            }

            return(count.ToString());
        }
Exemple #7
0
        public string SolveSecondStar(StreamReader reader)
        {
            var lines = StreamParsers.GetStreamAsStringList(reader);

            foreach (var line in lines)
            {
                var split       = line.Split(" (contains ");
                var ingredients = split[0].Split(null);
                var allergens   = split[1].Substring(0, split[1].Length - 1).Split(", ");

                foreach (var allergen in allergens)
                {
                    if (!PossibleIngredients.ContainsKey(allergen))
                    {
                        PossibleIngredients.Add(allergen, new HashSet <string>());
                        foreach (var ingredient in ingredients)
                        {
                            PossibleIngredients[allergen].Add(ingredient);
                        }
                    }
                    else
                    {
                        PossibleIngredients[allergen].IntersectWith(ingredients);
                    }
                }
            }

            var allergenToIngredient = new Dictionary <string, string>();

            while (allergenToIngredient.Count() < PossibleIngredients.Count())
            {
                foreach (var allergen in PossibleIngredients.Keys)
                {
                    if (PossibleIngredients[allergen].Count == 1)
                    {
                        var ingredient = PossibleIngredients[allergen].First();
                        allergenToIngredient.Add(allergen, ingredient);
                        foreach (var ingredients in PossibleIngredients.Values)
                        {
                            ingredients.Remove(ingredient);
                        }
                    }
                }
            }

            var a = allergenToIngredient.Keys.ToList <string>();

            a.Sort();
            var result = "";

            foreach (var allergen in a)
            {
                result += allergenToIngredient[allergen] + ",";
            }

            return(result.Substring(0, result.Length - 1));
        }
Exemple #8
0
        public string SolveFirstStar(StreamReader reader)
        {
            var lines         = StreamParsers.GetStreamAsLongIntList(reader);
            var cardPublicKey = lines[0];
            var doorPublicKey = lines[1];

            var doorLoops = ReverseTransform(DefaultSubject, doorPublicKey);

            return(TransformLoop(cardPublicKey, doorLoops).ToString());
        }
Exemple #9
0
        public string SolveSecondStar(StreamReader reader)
        {
            var  expressions = StreamParsers.GetStreamAsStringList(reader);
            long sum         = 0;

            foreach (var expression in expressions)
            {
                sum += EvaluateExpression(expression, '+');
            }
            return(sum.ToString());
        }
Exemple #10
0
        public string SolveSecondStar(StreamReader reader)
        {
            var listOfDefinitions = StreamParsers.GetStreamAsStringList(reader);

            BuildBagList(listOfDefinitions);

            // Includes shiny gold bag, subtract one for final answer
            int bagCount = CountInnerBags(ShinyGoldBagColor);

            return((bagCount - 1).ToString());
        }
Exemple #11
0
        public string SolveSecondStar(StreamReader reader)
        {
            var numbers = StreamParsers.GetStreamAsLongIntList(reader);
            var subList = findSubListEqualToN(numbers, FirstStarResult);

            if (subList == null)
            {
                throw new Exception($"Unable to find sub-list equal to {FirstStarResult}");
            }

            return((subList.Min() + subList.Max()).ToString());
        }
Exemple #12
0
        public string SolveSecondStar(StreamReader reader)
        {
            map = StreamParsers.GetStreamAsStringList(reader);
            var lastFlippedSeats = int.MaxValue;

            for (var flippedSeats = ApplyRules(Version.Gold); lastFlippedSeats - flippedSeats > 0; flippedSeats = ApplyRules(Version.Gold))
            {
                lastFlippedSeats = flippedSeats;
                //PrintMap();
            }
            return(CountAllOccupiedSeats().ToString());
        }
Exemple #13
0
        public string SolveFirstStar(StreamReader reader)
        {
            var listOfDefinitions = StreamParsers.GetStreamAsStringList(reader);

            BuildBagList(listOfDefinitions);

            var parentBags = new HashSet <string>();

            GetParentBags(ShinyGoldBagColor, parentBags);

            // Includes shiny gold bag, subtract one for answer
            return((parentBags.Count() - 1).ToString());
        }
Exemple #14
0
        public string SolveSecondStar(StreamReader reader)
        {
            var numberDict = new Dictionary <int, int>();

            // Read in file stream as list of ints
            var numberList = StreamParsers.GetStreamAsIntList(reader);

            foreach (var n in numberList)
            {
                // Count duplicate entries by incrementing the value in the dict
                if (numberDict.ContainsKey(n))
                {
                    numberDict[n] = numberDict[n] + 1;
                }
                else
                {
                    numberDict[n] = 1;
                }
            }

            // Iterate through each pair of expense report values
            for (int i = 0; i < numberList.Count; ++i)
            {
                for (int j = 0; j < numberList.Count; ++j)
                {
                    // Can't use the same expense report twice
                    if (i == j)
                    {
                        continue;
                    }

                    // Compute the missing number that we are looking for
                    int difference = TargetSum - (numberList[i] + numberList[j]);
                    if (numberDict.ContainsKey(difference))
                    {
                        // If the missing number is a duplicate, make sure that there is a duplicate number available
                        if (numberList[i] == difference || numberList[j] == difference)
                        {
                            if (numberDict[difference] == 1)
                            {
                                // Do not have an additional copy of that number we can use, continue
                                continue;
                            }
                        }
                        return((numberList[i] * numberList[j] * difference).ToString());
                    }
                }
            }

            throw new Exception($"Unable to find a set of three numbers that add to {TargetSum}");
        }
Exemple #15
0
        public string SolveFirstStar(StreamReader reader)
        {
            var instructionTextList = StreamParsers.GetStreamAsStringList(reader);
            var instructions        = BuildInstructionList(instructionTextList);

            try
            {
                RunProgram(instructions);
            }
            catch (InfiniteLoopException e)
            {
                return(e.AccumulatorValue.ToString());
            }

            throw new Exception("No infinite loop detected");
        }
Exemple #16
0
        public string SolveSecondStar(StreamReader reader)
        {
            var lines  = StreamParsers.GetStreamAsStringList(reader);
            var memory = new Dictionary <long, long>();
            List <List <int> > maskList = null;

            foreach (var line in lines)
            {
                if (line.Substring(0, 4) == "mask")
                {
                    var mask = line.Split(" = ")[1];
                    maskList = UpdateMaskList(mask);
                    //PrintMaskLists(maskList);
                }
                else
                {
                    var  match   = Regex.Match(line, MemWriteRegexString);
                    long address = Int64.Parse(match.Groups[1].Value);
                    long value   = Int64.Parse(match.Groups[2].Value);
                    var  addressAsBinaryString = LongIntToBinaryString(address, 36);
                    foreach (var mask in maskList)
                    {
                        var modifiedAddress = "";
                        for (int i = 0; i < 36; i++)
                        {
                            if (mask[i] == 1)
                            {
                                modifiedAddress += '1';
                            }
                            else if (mask[i] == 0)
                            {
                                modifiedAddress += '0';
                            }
                            else
                            {
                                // This is the case where the mask bit == -1, preserve original bit
                                modifiedAddress += addressAsBinaryString[i];
                            }
                        }
                        long actualAddress = Convert.ToInt64(modifiedAddress, 2);
                        memory[actualAddress] = value;
                    }
                }
            }

            return(memory.Values.Sum().ToString());
        }
Exemple #17
0
        public string SolveSecondStar(StreamReader reader)
        {
            var directions = StreamParsers.GetStreamAsStringList(reader);
            var ship       = new Ship(0, 0);
            var waypoint   = new Waypoint(10, 1);

            foreach (var direction in directions)
            {
                var action = direction[0];
                var param  = int.Parse(direction.Substring(1));

                switch (action)
                {
                case 'L':
                    waypoint.Rotate(param, false);
                    break;

                case 'R':
                    waypoint.Rotate(param, true);
                    break;

                case 'N':
                    waypoint.Move(Direction.North, param);
                    break;

                case 'E':
                    waypoint.Move(Direction.East, param);
                    break;

                case 'S':
                    waypoint.Move(Direction.South, param);
                    break;

                case 'W':
                    waypoint.Move(Direction.West, param);
                    break;

                case 'F':
                    ship.MoveTowardWaypoint(waypoint, param);
                    break;
                }
            }

            return(ship.GetManhattanDistance().ToString());
        }
Exemple #18
0
        public string SolveSecondStar(StreamReader reader)
        {
            var stringList = StreamParsers.GetStreamAsListOfDelimitedStrings(reader, ":".ToCharArray());

            int count = 0;

            foreach (var ruleAndPassword in stringList)
            {
                var rule     = ruleAndPassword[0].Trim();
                var password = ruleAndPassword[1].Trim();
                if (validatePassword(rule, password, 2))
                {
                    count++;
                }
            }

            return(count.ToString());
        }
Exemple #19
0
        public string SolveFirstStar(StreamReader reader)
        {
            var numberSet = new HashSet <int>();

            // Read in file stream as list of ints
            var numberList = StreamParsers.GetStreamAsIntList(reader);

            foreach (var n in numberList)
            {
                var difference = TargetSum - n;
                if (numberSet.Contains(difference))
                {
                    return((n * difference).ToString());
                }
                numberSet.Add(n);
            }

            throw new Exception($"Unable to find a pair of numbers that add to {TargetSum}");
        }
Exemple #20
0
        public string SolveFirstStar(StreamReader reader)
        {
            var lines  = StreamParsers.GetStreamAsStringList(reader);
            var memory = new Dictionary <long, long>();

            string mask = "";

            foreach (var line in lines)
            {
                if (line.Substring(0, 4) == "mask")
                {
                    mask = line.Split(" = ")[1];
                }
                else
                {
                    var  match               = Regex.Match(line, MemWriteRegexString);
                    var  address             = int.Parse(match.Groups[1].Value);
                    long value               = Int64.Parse(match.Groups[2].Value);
                    var  valueAsBinaryString = LongIntToBinaryString(value, 36);
                    var  modifiedValue       = "";
                    for (int i = 0; i < mask.Length; i++)
                    {
                        if (mask[i] == '1')
                        {
                            modifiedValue += '1';
                        }
                        else if (mask[i] == '0')
                        {
                            modifiedValue += '0';
                        }
                        else
                        {
                            modifiedValue += valueAsBinaryString[i];
                        }
                    }
                    long modifiedValueAsInt = Convert.ToInt64(modifiedValue, 2);
                    memory[address] = modifiedValueAsInt;
                }
            }

            return(memory.Values.Sum().ToString());
        }
Exemple #21
0
        public string SolveFirstStar(StreamReader reader)
        {
            var lines = StreamParsers.GetStreamAsStringList(reader);
            var index = BuildRules(lines);

            long count = 0;

            for (int i = index; i < lines.Count; i++)
            {
                var word = lines[i];
                int numMatches;
                var lastIndex = CheckRuleRepeat(word, 0, 0, out numMatches);
                if (numMatches == 1 && lastIndex == word.Length)
                {
                    count++;
                }
            }

            return(count.ToString());
        }
Exemple #22
0
        public string SolveSecondStar(StreamReader reader)
        {
            var instructionTextList = StreamParsers.GetStreamAsStringList(reader);
            var instructions        = BuildInstructionList(instructionTextList);

            try
            {
                // Build up "seen" jmp indices
                RunProgram(instructions, true);
            }
            catch
            {
                // Expect infinite loop
            }

            int acc            = -1;
            int jmpToSkipIndex = 0;

            while (acc == -1 && jmpToSkipIndex < SeenJmpIndices.Count())
            {
                try
                {
                    instructions[SeenJmpIndices[jmpToSkipIndex]].Type = OpCode.NOP;
                    acc = RunProgram(instructions);
                }
                catch
                {
                    // Expect to find many loops here, ignore
                }
                finally
                {
                    instructions[SeenJmpIndices[jmpToSkipIndex]].Type = OpCode.JMP;
                }

                jmpToSkipIndex++;
            }

            return(acc.ToString());
        }
Exemple #23
0
        public string SolveFirstStar(StreamReader reader)
        {
            var boardingPasses = StreamParsers.GetStreamAsStringList(reader);
            int maxId          = 0;

            foreach (var pass in boardingPasses)
            {
                var rowEncoding    = pass.Substring(0, 7);
                var columnEncoding = pass.Substring(7);

                var row    = GetRow(rowEncoding);
                var column = GetColumn(columnEncoding);

                var id = row * 8 + column;

                if (id > maxId)
                {
                    maxId = id;
                }
            }

            return(maxId.ToString());
        }
Exemple #24
0
        public string SolveFirstStar(StreamReader reader)
        {
            var numbers       = StreamParsers.GetStreamAsLongIntList(reader);
            var recentNumbers = new LinkedList <long>();

            for (int i = 0; i < WindowSize; i++)
            {
                recentNumbers.AddLast(numbers[i]);
            }

            for (int i = WindowSize; i < numbers.Count(); i++)
            {
                if (!isNumberValid(recentNumbers, numbers[i]))
                {
                    FirstStarResult = numbers[i];
                    return(numbers[i].ToString());
                }

                recentNumbers.RemoveFirst();
                recentNumbers.AddLast(numbers[i]);
            }

            throw new Exception("Could not find invalid number");
        }
Exemple #25
0
        // Note: Gross, lazy solution

        public string SolveFirstStar(StreamReader reader)
        {
            CubeSpace = new Dictionary <ValueTuple <int, int, int, int>, bool>();
            var cubes = StreamParsers.GetStreamAsStringList(reader);

            for (int y = 0; y < cubes.Count; y++)
            {
                for (int x = 0; x < cubes[y].Count(); x++)
                {
                    if (cubes[y][x] == '#')
                    {
                        CubeSpace.Add((x, y, 0, 0), true);
                    }
                }
            }

            int xMin   = -1;
            int yMin   = -1;
            int zMin   = -1;
            int xRange = cubes[0].Count() + 2;
            int yRange = cubes.Count + 2;
            int zRange = 3;

            var activeCubes = 0;

            for (int i = 1; i <= 6; i++)
            {
                activeCubes = 0;
                var newCubeSpace = new Dictionary <ValueTuple <int, int, int, int>, bool>();
                for (int z = zMin; z < zMin + zRange; z++)
                {
                    for (int y = yMin; y < yMin + yRange; y++)
                    {
                        for (int x = xMin; x < xMin + xRange; x++)
                        {
                            var isActive        = CubeSpace.ContainsKey((x, y, z, 0)) && CubeSpace[(x, y, z, 0)];
Exemple #26
0
        public string SolveFirstStar(StreamReader reader)
        {
            treeMap = StreamParsers.GetStreamAs2DIntArray(reader);

            return(CountTrees(3, 1).ToString());
        }