コード例 #1
0
        public static void Solve()
        {
            string         inputPath = FileUtils.GetProjectFilePath("Days/Day5/ProblemB/input.txt");
            string         text      = File.ReadAllText(inputPath);
            HashSet <char> chars     = new HashSet <char>();

            for (int i = 0; i < text.Length; i++)
            {
                char c = Char.ToLower(text[i]);
                if (!chars.Contains(c))
                {
                    chars.Add(c);
                }
            }

            int  bestVal = Int32.MaxValue;
            char bestC   = ' ';

            foreach (var c in chars)
            {
                int len = TestReaction(text, c);
                if (len < bestVal)
                {
                    bestVal = len;
                    bestC   = c;
                }
            }
            Console.WriteLine("Best pair to remove is " + bestC + " and it creates a polymer of length " + bestVal);
        }
コード例 #2
0
ファイル: Day1ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day1/ProblemA/input.txt");

            String[] lines = File.ReadAllLines(inputPath);
            int      sum   = 0;

            foreach (var line in lines)
            {
                string trim = line.Trim();
                if (!String.IsNullOrEmpty(trim))
                {
                    bool isPos = trim[0] == '+';
                    int  parsed;
                    if (Int32.TryParse(trim.Substring(1), out parsed))
                    {
                        if (isPos)
                        {
                            sum += parsed;
                        }
                        else
                        {
                            sum -= parsed;
                        }
                    }
                }
            }
            Log.WriteLine("Sum is " + sum);
        }
コード例 #3
0
ファイル: Day3BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day3/ProblemB/input.txt");

            using (var reader = new System.IO.StreamReader(inputPath))
            {
                string      line;
                List <Rect> allRects = new List <Rect>();
                while ((line = reader.ReadLine()) != null)
                {
                    string input = line.Trim();
                    if (!String.IsNullOrEmpty(input))
                    {
                        var rect = new Rect(input);
                        MarkUsage(rect);
                        allRects.Add(rect);
                    }
                }
                foreach (var rect in allRects)
                {
                    if (IsIsolated(rect))
                    {
                        Console.WriteLine(rect.Id + " had no overlaps");
                    }
                }
            }
        }
コード例 #4
0
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day23/ProblemA/input.txt");

            string[] lines = File.ReadAllLines(inputPath);
            int      count = 0;

            foreach (var line in lines)
            {
                string l = line.Trim();
                if (!string.IsNullOrEmpty(l))
                {
                    AllBots.Add(new Nanobot(l, count));
                    count++;
                }
            }

            Log.WriteLine("Loaded " + AllBots.Count + " bots");

            foreach (var bot in AllBots)
            {
                foreach (var candidate in AllBots)
                {
                    bot.AddNeighborIfInRange(candidate);
                }
            }

            AllBots.Sort(CompareByRange);

            Log.WriteLine("Strongest bot is " + AllBots[0].Debug());
        }
コード例 #5
0
ファイル: Problem25ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day25/ProblemA/input.txt");

            string[] lines = File.ReadAllLines(inputPath);
            int      count = 0;

            for (int i = 0; i < lines.Length; i++)
            {
                string l = lines[i].Trim();
                if (!string.IsNullOrEmpty(l))
                {
                    _allPoints.Add(new Point(l, count));
                    count++;
                }
            }

            Log.WriteLine("Added " + _allPoints.Count + " points");

            const int targetDistance = 3;

            for (int i = 0; i < _allPoints.Count; i++)
            {
                for (int j = 0; j < _allPoints.Count; j++)
                {
                    if (i != j)
                    {
                        long dist = _allPoints[i].Distance(_allPoints[j]);
                        if (dist <= targetDistance)
                        {
                            _allPoints[i].Neighbors.Add(_allPoints[j]);
                        }
                    }
                }
            }

            int constellationCount = 0;

            foreach (var point in _allPoints)
            {
                Constellation existing;
                if (!_membership.TryGetValue(point, out existing))
                {
                    BuildConstellation(point, constellationCount);
                    constellationCount++;
                }
            }

            int nonDegenerateCount = 0;

            foreach (var c in _allConstellations)
            {
                if (c.Contents.Count > 1)
                {
                    nonDegenerateCount++;
                }
            }

            Log.WriteLine("Found " + constellationCount + " constellations - " + nonDegenerateCount + " were non degenerate");
        }
コード例 #6
0
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day2/ProblemA/input.txt");

            int[] histogramBuffer = new int[26];             // Simplifying assumption, our input is all lower case and only alphabetical
            int   twoCountSum     = 0;
            int   threeCountSum   = 0;

            bool foundTwoCount;
            bool foundThreeCount;

            using (var reader = new System.IO.StreamReader(inputPath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    GenerateChecksumOutputs(line.Trim(), histogramBuffer, out foundTwoCount, out foundThreeCount);
                    if (foundTwoCount)
                    {
                        twoCountSum++;
                    }

                    if (foundThreeCount)
                    {
                        threeCountSum++;
                    }
                }
            }
            Log.WriteLine("Checksum is " + twoCountSum * threeCountSum);
        }
コード例 #7
0
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day10/ProblemA/input.txt");

            String[] lines = File.ReadAllLines(inputPath);

            string        outpath = "/scratch/Day10Images";
            DirectoryInfo di      = new DirectoryInfo(outpath);

            if (!di.Exists)
            {
                di.Create();
            }

            List <Point> points = new List <Point>();

            foreach (var line in lines)
            {
                string l = line.Trim();
                if (!string.IsNullOrEmpty(l))
                {
                    points.Add(new Point(l));
                }
            }

            for (int i = 0; i < FramesToSimulate; i++)
            {
                string fileName = i + ".png";
                RenderGameboard(points, Path.Combine(outpath, fileName));
                foreach (var p in points)
                {
                    p.Advance();
                }
            }
        }
コード例 #8
0
ファイル: Day15ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day15/ProblemA/input.txt");

            String[]         lines = File.ReadAllLines(inputPath);
            CombatSimulation sim   = new CombatSimulation(lines);

            sim.DoSimulation();
        }
コード例 #9
0
ファイル: Day8BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day8/ProblemB/input.txt");
            string text      = File.ReadAllText(inputPath);

            string[] parts = text.Split(' ');
            Tree     t     = new Tree(parts);

            Log.WriteLine("Total value is " + t.TotalValue);
        }
コード例 #10
0
        public static void Solve()
        {
            const int targetSumDistance = 10000;
            string    inputPath         = FileUtils.GetProjectFilePath("Days/Day6/ProblemB/input.txt");

            string[]     lines  = File.ReadAllLines(inputPath);
            List <Point> points = new List <Point>();
            int          minX   = Int32.MaxValue;
            int          minY   = Int32.MaxValue;
            int          maxX   = Int32.MinValue;
            int          maxY   = Int32.MinValue;

            foreach (var line in lines)
            {
                var p = new Point(line);
                if (p.X < minX)
                {
                    minX = p.X;
                }
                if (p.Y < minY)
                {
                    minY = p.Y;
                }
                if (p.X > maxX)
                {
                    maxX = p.X;
                }
                if (p.Y > maxY)
                {
                    maxY = p.Y;
                }
                points.Add(p);
            }
            Log.WriteLine("Grid is between " + minX + "," + minY + " and " + maxX + "," + maxY);
            HashSet <int> distances = new HashSet <int>();
            int           region    = 0;

            for (int i = minX; i <= maxX; i++)
            {
                for (int j = minY; j <= maxY; j++)
                {
                    int sumDist = 0;
                    foreach (var p in points)
                    {
                        sumDist += p.ManhattanDistance(i, j);
                    }

                    if (sumDist < targetSumDistance)
                    {
                        region++;
                    }
                }
            }
            Log.WriteLine("Total region size is " + region);
        }
コード例 #11
0
ファイル: Day13ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day13/ProblemA/input.txt");

            String[]       lines = File.ReadAllLines(inputPath);
            MinecartSystem ms    = new MinecartSystem(lines);

            ms.Simulate();
        }
コード例 #12
0
ファイル: Day1BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day1/ProblemB/input.txt");

            String[] lines = File.ReadAllLines(inputPath);
            int      sum   = 0;
            bool     found = false;
            int      iter  = 0;

            while (!found)
            {
                foreach (var line in lines)
                {
                    string trim = line.Trim();
                    if (!String.IsNullOrEmpty(trim))
                    {
                        bool isPos = trim[0] == '+';
                        int  parsed;
                        if (Int32.TryParse(trim.Substring(1), out parsed))
                        {
                            if (isPos)
                            {
                                sum += parsed;
                            }
                            else
                            {
                                sum -= parsed;
                            }

                            if (_seen.Contains(sum))
                            {
                                Log.WriteLine("Found a duplicate at " + sum);
                                found = true;
                                break;
                            }
                            else
                            {
                                _seen.Add(sum);
                            }
                        }
                    }
                }
                iter++;
                if (found)
                {
                    break;
                }
                else
                {
                    Log.WriteLine("No duplicates found after " + iter + " iterations");
                }
            }
        }
コード例 #13
0
ファイル: Day20ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day20/ProblemA/input.txt");
            string input     = File.ReadAllText(inputPath).Trim();



            input = input.Substring(1, input.Length - 2);
            Log.WriteLine("Generating all paths for " + input);

            List <string> allPaths   = new List <string>();
            string        inProgress = "";

            try
            {
                AllPaths(String.Empty, input, allPaths);
            }
            catch (Exception ex)
            {
                Log.WriteLine("Caught exception " + ex.Message + " at " + ex.StackTrace.Substring(0, 1000));
                return;
            }


            allPaths.Sort(CompareStringsByLength);

            Log.WriteLine("Found " + allPaths.Count + " total paths - longest path was " + allPaths[0].Length);



            foreach (var path in allPaths)
            {
                //Log.WriteLine(path);
            }

            /*
             * int programStartPoint = sets * 4;
             * for (int i = programStartPoint; i < allLines.Length; i++)
             * {
             *      string line = allLines[i].Trim();
             *      if (!string.IsNullOrEmpty(line))
             *      {
             *              int[] commandArgs = InstructionTestSet.ParseCommand(line);
             *              string opCode = _opCodeIds[commandArgs[0]][0];
             *              var op = _allOpCodes[opCode];
             *              if (!op.Execute(commandArgs, registers))
             *              {
             *                      Log.WriteLine("Failed to execute line " + i);
             *              }
             *      }
             * }*/
        }
コード例 #14
0
ファイル: Day9ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day9/ProblemA/input.txt");
            string text      = File.ReadAllText(inputPath);

            string[] parts = text.Split(';');
            _numPlayers    = Int32.Parse(_numericRgx.Replace(parts[0], ""));
            _highestMarble = Int32.Parse(_numericRgx.Replace(parts[1], ""));

            Log.WriteLine("Starting a game with " + _numPlayers + " players and highest marble value " + _highestMarble);

            DoInitialSetup();
            PlayGame();
            LogWinner();
        }
コード例 #15
0
        public static void Solve()
        {
            using (var timer = new Timer("Day 1A Problem"))
            {
                int    sum       = 0;
                string inputPath = FileUtils.GetProjectFilePath("Days/Day1/ProblemAExtra/input.txt");
                foreach (string readLine in File.ReadLines(inputPath))
                {
                    int result = 0;
                    if (int.TryParse(readLine, out result))
                    {
                        sum += result;
                    }
                }

                Log.WriteLine("Sum is " + sum);
            }
        }
コード例 #16
0
ファイル: Day15BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day15/ProblemB/input.txt");

            String[] lines         = File.ReadAllLines(inputPath);
            int      startingPower = 3;

            for (int i = startingPower; i <= 1000; i++)
            {
                // TODO - This should be doing a binary search, but this problem has exhausted me :p
                CombatSimulation sim = new CombatSimulation(lines, i);
                var result           = sim.DoSimulation();
                Log.WriteLine("Completed simulation for attack power " + i + " Winner: " + result.Victor + " with alive elves " + result.ElfAliveCount + "/" + result.ElfParticipantCount);
                if (result.Victor == 'E' && result.ElfAliveCount == result.ElfParticipantCount)
                {
                    Log.WriteLine("Finished! - Final power was " + i);
                }
            }
        }
コード例 #17
0
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day3/ProblemA/input.txt");

            using (var reader = new System.IO.StreamReader(inputPath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string input = line.Trim();
                    if (!String.IsNullOrEmpty(input))
                    {
                        MarkUsage(new Rect(input));
                    }
                }
            }
            Log.WriteLine(Overlaps.Count + " tiles were overlapping");
        }
コード例 #18
0
ファイル: Day2BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            int sum = 0;

            string        inputPath  = FileUtils.GetProjectFilePath("Days/Day2/ProblemB/input.txt");
            List <string> allStrings = new List <string>();

            using (var reader = new System.IO.StreamReader(inputPath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    allStrings.Add(line.Trim());
                }
            }

            bool pairFound = false;

            for (int i = 0; i < allStrings.Count; i++)
            {
                for (int j = i + 1; j < allStrings.Count; j++)
                {
                    if (ApproximatelyEqual(allStrings[i], allStrings[j]))
                    {
                        Log.WriteLine("Match found - common substring is " + GenerateCommonSubstring(allStrings[i], allStrings[j]));
                        pairFound = true;
                        break;
                    }
                }

                if (pairFound)
                {
                    break;
                }
            }

            if (!pairFound)
            {
                Log.WriteLine("No checksum found in data set");
            }
        }
コード例 #19
0
        public static void Solve()
        {
            const int WorkSlice = 1000000;

            using (var timer = new Timer("Day 1A Problem"))
            {
                string   inputPath = FileUtils.GetProjectFilePath("Days/Day1/ProblemAExtra/input.txt");
                String[] lines     = File.ReadAllLines(inputPath);

                List <Task <int> > lst = new List <Task <int> >();
                int  startLine         = 0;
                bool foundEnd          = false;
                while (true)
                {
                    int endLine = startLine + WorkSlice;

                    if (endLine >= lines.Length)
                    {
                        endLine  = lines.Length - 1;
                        foundEnd = true;
                    }
                    lst.Add(CreateJob(lines, startLine, endLine));
                    if (foundEnd)
                    {
                        break;
                    }

                    startLine = endLine + 1;
                }

                Task <int>[] tasks = lst.ToArray();
                Log.WriteLine("Awaiting " + tasks.Length + " tasks");
                Task.WaitAll(tasks);
                int sum = 0;
                for (int i = 0; i < tasks.Length; i++)
                {
                    sum += tasks[i].Result;
                }
                Log.WriteLine("Sum is " + sum);
            }
        }
コード例 #20
0
ファイル: Day16ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day16/ProblemA/input.txt");

            string[] allLines = File.ReadAllLines(inputPath);

            List <InstructionTestSet> tests = new List <InstructionTestSet>();
            int sets = 0;

            for (int i = 0; i < allLines.Length; i++)
            {
                string line = allLines[i];
                if (line.StartsWith("Before"))
                {
                    tests.Add(InstructionTestSet.Parse(allLines[i], allLines[i + 1], allLines[i + 2], sets));
                    sets++;
                }
            }
            Log.WriteLine("Beginning " + tests.Count + " tests");

            BuildOpCodes();

            foreach (var set in tests)
            {
                PerformTest(set);
            }

            int totalAmbigious = 0;

            foreach (var set in tests)
            {
                if (set.NumMatchingOpCodes >= 3)
                {
                    totalAmbigious++;
                }
                //Log.WriteLine("Test number " + set.TestNumber + " had " + set.NumMatchingOpCodes + " matching opcodes");
            }
            Log.WriteLine(totalAmbigious + " tests had ambigious op codes");
        }
コード例 #21
0
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day5/ProblemA/input.txt");
            string text      = File.ReadAllText(inputPath);
            int    index     = 0;
            bool   didReact;

            while (index < text.Length)
            {
                didReact = false;
                if (index > 0)
                {
                    if (DoesReact(text[index], text[index - 1]))
                    {
                        didReact = true;
                        text     = text.Remove(index, 1);
                        index--;
                        text = text.Remove(index, 1);
                    }
                }
                else if (index < text.Length - 1)
                {
                    if (DoesReact(text[index], text[index + 1]))
                    {
                        didReact = true;
                        text     = text.Remove(index + 1, 1);
                        text     = text.Remove(index, 1);
                    }
                }

                if (!didReact)
                {
                    index++;
                }
            }

            Log.WriteLine(text.Length);
        }
コード例 #22
0
ファイル: Day12ASolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day12/ProblemA/input.txt");

            String[] lines = File.ReadAllLines(inputPath);

            string initialState = lines[0];

            initialState = initialState.Split(':')[1].Trim();

            // Buffer out room equal to the number of generations we want to simulate
            List <char> initialBuffer = new List <char>();

            for (int i = 0; i <= NumGenerations + 1; i++)
            {
                initialBuffer.Add(Dead);
            }
            initialBuffer.AddRange(initialState.ToCharArray());
            for (int i = 0; i <= NumGenerations + 1; i++)
            {
                initialBuffer.Add(Dead);
            }

            CurrentGeneration = initialBuffer.ToArray();
            NextGeneration    = initialBuffer.ToArray();


            for (int i = 1; i < lines.Length; i++)
            {
                string l = lines[i].Trim();
                if (!string.IsNullOrEmpty(l))
                {
                    string rule    = l.Substring(0, l.IndexOf('=')).Trim();
                    char   outcome = l.Substring(l.IndexOf('>') + 1).Trim()[0];
                    Ruleset[rule] = outcome;
                }
            }

            Log.WriteLine("Beginning simulation for initial state of size " + initialState.Length + " num generations: " + NumGenerations);
            StringBuilder sb = new StringBuilder();

            Log.WriteLine("[" + 0 + "]" + new String(CurrentGeneration));
            for (int g = 1; g <= NumGenerations; g++)
            {
                for (int i = 0; i < CurrentGeneration.Length; i++)
                {
                    if (i < 2 || i > CurrentGeneration.Length - 3)
                    {
                        NextGeneration[i] = CurrentGeneration[i];
                        continue;
                    }

                    sb.Clear();
                    sb.Append(CurrentGeneration[i - 2]);
                    sb.Append(CurrentGeneration[i - 1]);
                    sb.Append(CurrentGeneration[i]);
                    sb.Append(CurrentGeneration[i + 1]);
                    sb.Append(CurrentGeneration[i + 2]);
                    char outcome;
                    if (Ruleset.TryGetValue(sb.ToString(), out outcome))
                    {
                        NextGeneration[i] = outcome;
                    }
                    else
                    {
                        Log.WriteLine(i + " No rule for " + sb.ToString());
                        NextGeneration[i] = Dead;
                    }
                }

                NextGeneration.CopyTo(CurrentGeneration, 0);
                string turn = g.ToString();
                if (g < 10)
                {
                    turn = "0" + turn;
                }
                Log.WriteLine("[" + turn + "]" + new String(CurrentGeneration));
            }

            int sum = 0;

            for (int i = 0; i < CurrentGeneration.Length; i++)
            {
                if (CurrentGeneration[i] == Alive)
                {
                    sum += (i - (NumGenerations + 2));
                }
            }
            Log.WriteLine("Simulation completed check sum is " + sum);
        }
コード例 #23
0
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day20/ProblemB/input.txt");
            string input     = File.ReadAllText(inputPath).Trim();

            for (int i = 0; i < _bestTiles.Length; i++)
            {
                _bestTiles[i] = Int32.MaxValue;
            }


            input = input.Substring(1, input.Length - 2);
            Log.WriteLine("Generating all paths for " + input);

            List <string> allPaths   = new List <string>();
            string        inProgress = "";

            try
            {
                AllPaths(String.Empty, 0, 0, input, allPaths);
            }
            catch (Exception ex)
            {
                Log.WriteLine("Caught exception " + ex.Message + " at " + ex.StackTrace.Substring(0, 1000));
                return;
            }


            //allPaths.Sort(CompareStringsByLength);

            //Log.WriteLine("Found " + allPaths.Count + " total paths - longest path was " + allPaths[0].Length);



            int tx;
            int ty;
            int pathable = 0;
            int minLen   = 1000;

            for (int i = 0; i < _bestTiles.Length; i++)
            {
                int len = _bestTiles[i];
                if (len < Int32.MaxValue && len >= minLen)
                {
                    pathable++;
                }
            }
            Log.WriteLine("Found " + pathable + " rooms with a minumum length of " + minLen);

            /*
             * int programStartPoint = sets * 4;
             * for (int i = programStartPoint; i < allLines.Length; i++)
             * {
             *      string line = allLines[i].Trim();
             *      if (!string.IsNullOrEmpty(line))
             *      {
             *              int[] commandArgs = InstructionTestSet.ParseCommand(line);
             *              string opCode = _opCodeIds[commandArgs[0]][0];
             *              var op = _allOpCodes[opCode];
             *              if (!op.Execute(commandArgs, registers))
             *              {
             *                      Log.WriteLine("Failed to execute line " + i);
             *              }
             *      }
             * }*/
        }
コード例 #24
0
ファイル: Day23BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day23/ProblemB/input.txt");

            string[] lines = File.ReadAllLines(inputPath);
            int      count = 0;

            foreach (var line in lines)
            {
                string l = line.Trim();
                if (!string.IsNullOrEmpty(l))
                {
                    Nanobot bot = new Nanobot(l, count);
                    AllBots.Add(bot);
                    count++;
                }
            }

            using (var ctx = new Context())
            {
                using (var opt = ctx.MkOptimize())
                {
                    ArithExpr X = (ArithExpr)ctx.MkConst("x", ctx.MkIntSort());
                    ArithExpr Y = (ArithExpr)ctx.MkConst("y", ctx.MkIntSort());
                    ArithExpr Z = (ArithExpr)ctx.MkConst("z", ctx.MkIntSort());

                    ArithExpr zero   = (ArithExpr)ctx.MkNumeral(0, ctx.IntSort);
                    ArithExpr one    = (ArithExpr)ctx.MkNumeral(1, ctx.IntSort);
                    ArithExpr negOne = (ArithExpr)ctx.MkNumeral(-1, ctx.IntSort);


                    List <ArithExpr> signals = new List <ArithExpr>();

                    foreach (var bot in AllBots)
                    {
                        ArithExpr dX = ctx.MkSub(X, (ArithExpr)ctx.MkNumeral(bot.X, ctx.MkIntSort()));
                        ArithExpr dY = ctx.MkSub(Y, (ArithExpr)ctx.MkNumeral(bot.Y, ctx.MkIntSort()));
                        ArithExpr dZ = ctx.MkSub(Z, (ArithExpr)ctx.MkNumeral(bot.Z, ctx.MkIntSort()));

                        ArithExpr aDX = (ArithExpr)ctx.MkITE(ctx.MkGe(dX, zero), dX, ctx.MkMul(dX, negOne));
                        ArithExpr aDY = (ArithExpr)ctx.MkITE(ctx.MkGe(dY, zero), dY, ctx.MkMul(dY, negOne));
                        ArithExpr aDZ = (ArithExpr)ctx.MkITE(ctx.MkGe(dZ, zero), dZ, ctx.MkMul(dZ, negOne));

                        ArithExpr dist = ctx.MkAdd(aDX, aDY, aDZ);

                        signals.Add((ArithExpr)ctx.MkITE(ctx.MkLe(dist, ctx.MkInt(bot.Range)), one, zero));
                    }

                    var totalSignals = ctx.MkAdd(signals);
                    opt.MkMaximize(totalSignals);

                    ArithExpr DX = (ArithExpr)ctx.MkITE(ctx.MkGe(X, zero), X, ctx.MkMul(X, negOne));
                    ArithExpr DY = (ArithExpr)ctx.MkITE(ctx.MkGe(Y, zero), Y, ctx.MkMul(Y, negOne));
                    ArithExpr DZ = (ArithExpr)ctx.MkITE(ctx.MkGe(Z, zero), Z, ctx.MkMul(Z, negOne));

                    ArithExpr distFromOrigin = ctx.MkAdd(DX, DY, DZ);

                    opt.MkMinimize(distFromOrigin);
                    opt.Check();
                    var model = opt.Model;
                    Log.WriteLine(model.ToString());
                }
            }
        }
コード例 #25
0
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day7/ProblemB/input.txt");

            string[] lines = File.ReadAllLines(inputPath);

            const int DepPivot       = 5;
            const int SubPivot       = 36;
            const int MaxRunningJobs = 5;

            Job[] queue         = new Job[26];
            Job[] runnableQueue = new Job[26];
            Job[] runningQueue  = new Job[26];
            int   queuedJobs    = 0;
            int   runnableJobs  = 0;
            int   runningJobs   = 0;

            foreach (var line in lines)
            {
                string l = line.Trim();
                if (string.IsNullOrEmpty(l))
                {
                    continue;
                }
                char dep     = line[DepPivot];
                char subject = line[SubPivot];
                Job  depJob  = queue[dep - CharIntegerOffset];
                if (depJob == null)
                {
                    depJob = new Job(dep);
                    queue[depJob.LetterId] = depJob;
                    queuedJobs++;
                }

                Job j = queue[subject - CharIntegerOffset];
                if (j == null)
                {
                    j = new Job(subject);
                    queue[j.LetterId] = j;
                    queuedJobs++;
                }
                j.AddDependency(depJob);
            }
            int           totalSeconds = 0;
            StringBuilder sb           = new StringBuilder();

            while (queuedJobs > 0 || runnableJobs > 0 || runningJobs > 0)
            {
                if (queuedJobs > 0)
                {
                    for (int i = 0; i < queue.Length; i++)
                    {
                        if (queue[i] != null)
                        {
                            if (queue[i].Runnable)
                            {
                                var j = queue[i];
                                queue[i]         = null;
                                runnableQueue[i] = j;
                                queuedJobs--;
                                runnableJobs++;
                            }
                        }
                    }
                }

                if (runnableJobs > 0 && runningJobs < MaxRunningJobs)
                {
                    for (int i = 0; i < runnableQueue.Length; i++)
                    {
                        if (runnableQueue[i] != null)
                        {
                            var j = runnableQueue[i];
                            runnableQueue[i] = null;
                            runningQueue[i]  = j;
                            runnableJobs--;
                            runningJobs++;
                            if (runningJobs >= MaxRunningJobs)
                            {
                                break;
                            }
                        }
                    }
                }

                if (runningJobs > 0)
                {
                    for (int i = 0; i < runningQueue.Length; i++)
                    {
                        if (runningQueue[i] != null)
                        {
                            runningQueue[i].DoWork(totalSeconds);
                            if (runningQueue[i].IsComplete)
                            {
                                var completedJob = runningQueue[i];
                                runningQueue[i] = null;
                                runningJobs--;
                                for (int j = 0; j < queue.Length; j++)
                                {
                                    if (queue[j] != null)
                                    {
                                        queue[j].MarkDependencyCompleted(completedJob);
                                    }
                                }
                            }
                        }
                    }
                    totalSeconds++;
                }
            }
            Log.WriteLine("Took " + MaxRunningJobs + " workers a total of " + totalSeconds + " seconds to complete");
        }
コード例 #26
0
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day16/ProblemB/input.txt");

            string[] allLines = File.ReadAllLines(inputPath);

            List <InstructionTestSet> tests = new List <InstructionTestSet>();
            int sets = 0;

            for (int i = 0; i < allLines.Length; i++)
            {
                string line = allLines[i];
                if (line.StartsWith("Before"))
                {
                    tests.Add(InstructionTestSet.Parse(allLines[i], allLines[i + 1], allLines[i + 2], sets));
                    sets++;
                }
            }


            BuildOpCodes();
            //Log.WriteLine("Stage 1 - Figure out the minimum set of commands supported by the data");
            foreach (var set in tests)
            {
                PerformTest(set);
                int           instructionId = set.Command[0];
                List <string> existing;
                if (_opCodeIds.TryGetValue(instructionId, out existing))
                {
                    List <string> cp = new List <string>();
                    foreach (var str in existing)
                    {
                        if (set.MatchingOpCodes.Contains(str))                         // Check to see if our hypothesis is still supported
                        {
                            cp.Add(str);
                        }
                    }
                    _opCodeIds[instructionId] = cp;
                }
                else
                {
                    existing = new List <string>();                    // This is the first time we have encountered this command, include all possible options
                    existing.AddRange(set.MatchingOpCodes);
                    _opCodeIds[instructionId] = existing;
                }
            }


            //DumpOpCodeState();

            //Log.WriteLine("Stage 2 - Repeatedly remove unique commands until we have everything disambiguated");
            HashSet <string> removalList = new HashSet <string>();

            while (OpCodesAreAmbiguous())
            {
                string toRemove = null;

                foreach (var kvp in _opCodeIds)
                {
                    if (kvp.Value.Count == 1 && !removalList.Contains(kvp.Value[0]))
                    {
                        toRemove = kvp.Value[0];
                        removalList.Add(kvp.Value[0]);
                        break;
                    }
                }
                if (toRemove == null)
                {
                    break;
                }

                foreach (var kvp in _opCodeIds)
                {
                    if (kvp.Value.Count > 1 && kvp.Value.Contains(toRemove))
                    {
                        kvp.Value.Remove(toRemove);
                    }
                }
            }

            //Log.WriteLine("Finished figuring out commands");
            //DumpOpCodeState();

            int[] registers = new int[4];

            int programStartPoint = sets * 4;

            for (int i = programStartPoint; i < allLines.Length; i++)
            {
                string line = allLines[i].Trim();
                if (!string.IsNullOrEmpty(line))
                {
                    int[]  commandArgs = InstructionTestSet.ParseCommand(line);
                    string opCode      = _opCodeIds[commandArgs[0]][0];
                    var    op          = _allOpCodes[opCode];
                    if (!op.Execute(commandArgs, registers))
                    {
                        Log.WriteLine("Failed to execute line " + i);
                    }
                }
            }
            Log.WriteLine("Program finished, register state is " + DumpRegisters(registers));
        }
コード例 #27
0
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day6/ProblemA/input.txt");

            string[]     lines  = File.ReadAllLines(inputPath);
            List <Point> points = new List <Point>();
            int          minX   = Int32.MaxValue;
            int          minY   = Int32.MaxValue;
            int          maxX   = Int32.MinValue;
            int          maxY   = Int32.MinValue;

            foreach (var line in lines)
            {
                var p = new Point(line);
                if (p.X < minX)
                {
                    minX = p.X;
                }
                if (p.Y < minY)
                {
                    minY = p.Y;
                }
                if (p.X > maxX)
                {
                    maxX = p.X;
                }
                if (p.Y > maxY)
                {
                    maxY = p.Y;
                }
                points.Add(p);
            }
            Log.WriteLine("Grid is between " + minX + "," + minY + " and " + maxX + "," + maxY);
            Point         bestPoint = null;
            HashSet <int> distances = new HashSet <int>();

            for (int i = minX; i <= maxX; i++)
            {
                for (int j = minY; j <= maxY; j++)
                {
                    int   closestDistance = Int32.MaxValue;
                    Point winningPoint    = null;
                    //distances.Clear();
                    foreach (var p in points)
                    {
                        int dist = p.ManhattanDistance(i, j);

                        if (dist == closestDistance)                         // Bounce out if one or more distancs is duped
                        {
                            winningPoint = null;
                            continue;
                        }
                        //distances.Add(dist);
                        if (dist < closestDistance)
                        {
                            winningPoint    = p;
                            closestDistance = dist;
                        }
                    }

                    if (winningPoint != null)
                    {
                        winningPoint.OwnedTerritory++;
                        if (bestPoint == null || bestPoint.OwnedTerritory < winningPoint.OwnedTerritory)
                        {
                            bestPoint = winningPoint;
                        }
                    }
                }
            }

            Log.WriteLine("best point is " + bestPoint.X + "," + bestPoint.Y + " with territory " + bestPoint.OwnedTerritory);
        }
コード例 #28
0
        public static void Solve()
        {
            _maxX = 2000;


            string inputPath = FileUtils.GetProjectFilePath("Days/Day17/ProblemA/input.txt");

            String[] lines = File.ReadAllLines(inputPath);

            List <Vein> veins    = new List <Vein>();
            Int32       deepestY = Int32.MinValue;

            _smallestYPoint = Int32.MaxValue;
            foreach (var line in lines)
            {
                var l = line.Trim();
                if (!string.IsNullOrEmpty(l) && !l.StartsWith('/'))
                {
                    Vein v = new Vein(l);
                    if (v.MaxY > deepestY)
                    {
                        deepestY = v.MaxY;
                    }

                    if (v.MinY < _smallestYPoint)
                    {
                        _smallestYPoint = v.MinY;
                    }

                    veins.Add(v);
                }
            }

            Log.WriteLine("Parsed " + veins.Count + " lowest vein was " + deepestY);
            _maxY          = deepestY + 1;
            _largestYPoint = deepestY;
            _tiles         = new Tile[_maxX * _maxY];

            for (int i = 0; i < _maxX; i++)
            {
                for (int j = 0; j < _maxY; j++)
                {
                    Tile t = new Tile();
                    t.TileIndex         = GetTileIndex(i, j);
                    t.X                 = i;
                    t.Y                 = j;
                    t.TileType          = TileType.Sand;
                    _tiles[t.TileIndex] = t;
                }
            }

            for (int i = 0; i < _tiles.Length; i++)
            {
                var t = _tiles[i];
                t.Left   = GetTile(t.X - 1, t.Y);
                t.Bottom = GetTile(t.X, t.Y + 1);
                t.Right  = GetTile(t.X + 1, t.Y);
            }


            foreach (var vein in veins)
            {
                for (int i = vein.MinX; i <= vein.MaxX; i++)
                {
                    for (int j = vein.MinY; j <= vein.MaxY; j++)
                    {
                        GetTile(i, j).TileType = TileType.Clay;
                    }
                }
            }


            var fountain = GetTile(500, 0);

            fountain.TileType = TileType.Fountain;

            Flood(fountain, null);
            RenderGameBoard();

            Log.WriteLine("Total tiles flooded: " + FloodCount);
        }
コード例 #29
0
ファイル: Day12BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            string inputPath = FileUtils.GetProjectFilePath("Days/Day12/ProblemB/input.txt");

            String[] lines = File.ReadAllLines(inputPath);

            string initialState = lines[0];

            initialState = initialState.Split(':')[1].Trim();

            // Buffer out room equal to the number of generations we want to simulate
            List <char> initialBuffer = new List <char>();

            for (int i = 0; i <= NumGenerations + 1; i++)
            {
                initialBuffer.Add(Dead);
            }
            initialBuffer.AddRange(initialState.ToCharArray());
            for (int i = 0; i <= NumGenerations + 1; i++)
            {
                initialBuffer.Add(Dead);
            }

            CurrentGeneration = initialBuffer.ToArray();
            NextGeneration    = initialBuffer.ToArray();


            for (int i = 1; i < lines.Length; i++)
            {
                string l = lines[i].Trim();
                if (!string.IsNullOrEmpty(l))
                {
                    string rule    = l.Substring(0, l.IndexOf('=')).Trim();
                    char   outcome = l.Substring(l.IndexOf('>') + 1).Trim()[0];
                    Ruleset[rule] = outcome;
                }
            }

            Log.WriteLine("Beginning simulation for initial state of size " + initialState.Length + " num generations: " + NumGenerations);
            StringBuilder sb                  = new StringBuilder();
            int           prevGenSum          = 0;
            int           prevDelta           = Int32.MaxValue;
            const int     targetSimilarFrames = 100;
            int           numSimFrames        = 0;

            //Log.WriteLine("["+0+"]" + new String(CurrentGeneration));
            for (int g = 1; g <= NumGenerations; g++)
            {
                for (int i = 0; i < CurrentGeneration.Length; i++)
                {
                    if (i < 2 || i > CurrentGeneration.Length - 3)
                    {
                        NextGeneration[i] = CurrentGeneration[i];
                        continue;
                    }

                    sb.Clear();
                    sb.Append(CurrentGeneration[i - 2]);
                    sb.Append(CurrentGeneration[i - 1]);
                    sb.Append(CurrentGeneration[i]);
                    sb.Append(CurrentGeneration[i + 1]);
                    sb.Append(CurrentGeneration[i + 2]);
                    char outcome;
                    if (Ruleset.TryGetValue(sb.ToString(), out outcome))
                    {
                        NextGeneration[i] = outcome;
                    }
                    else
                    {
                        Log.WriteLine(i + " No rule for " + sb.ToString());
                        NextGeneration[i] = Dead;
                    }
                }

                NextGeneration.CopyTo(CurrentGeneration, 0);
                int currSum = GetCheckSum();
                int delta   = currSum - prevGenSum;
                if (delta == prevDelta)
                {
                    numSimFrames++;
                    if (numSimFrames == targetSimilarFrames)
                    {
                        Log.WriteLine("Convergence detected at generation " + g + " : " + delta);
                        long finalChecksum = currSum + (ProjectedGeneration - g) * delta;
                        Log.WriteLine("Projected checksum after " + ProjectedGeneration + " is " + finalChecksum);
                        break;
                    }
                }
                else
                {
                    numSimFrames = 0;
                }

                prevGenSum = currSum;
                prevDelta  = delta;
            }


            //Log.WriteLine("Simulation completed check sum is " + sum);
        }
コード例 #30
0
ファイル: Day19BSolver.cs プロジェクト: jmcguirk/aoc-2018
        public static void Solve()
        {
            int sum = 0;

            string inputPath = FileUtils.GetProjectFilePath("Days/Day19/ProblemB/input.txt");

            string[] allLines = File.ReadAllLines(inputPath);

            /* NOTE - Leaving this with a description of how we arrived at the solution vs actual code (which will never really terminate)
             *
             * - Looked at assembly and register state
             * - Converted into pseudo code
             * - Converted pseudo code into C#
             * - Dumped register state at various points
             * - Deduced it was a sloppy way of calculating a sum of factors of a number
             * - Factorized number by hand and summed in excel :)
             *
             * long r0 = 0;
             * long r1 = 1;
             * long r2 = 10551428;
             * long r3 = 10550400;
             * long r4 = 1;
             *
             * while(r1 < r2){
             *      r3 = r1 * r4;
             *      if(r3 == r2){
             *              r0 += r1;
             *      }
             *      r4++;
             *      if(r4 > r2){
             *              r1++;
             *              if (r1 % 100000 == 0)
             *              {
             *                      Log.WriteLine("Iter register state " + r0 + "," + r1 + "," + r2 + "," + r3 + "," + r4);
             *              }
             *      }
             * }
             * Log.WriteLine("Final register state " + r0 + "," + r1 + "," + r2 + "," + r3 + "," + r4); */

            /*
             * List<Instruction> instructions = new List<Instruction>();
             * int ip = -1;
             * for(int i = 0; i < allLines.Length; i++)
             * {
             *      string line = allLines[i].Trim();
             *      if (line.StartsWith("#ip"))
             *      {
             *              ip = Int32.Parse(line.Split(' ')[1]);
             *      }
             *      else
             *      {
             *              instructions.Add(Instruction.Parse(line));
             *      }
             * }
             *
             *
             * BuildOpCodes();
             *
             * int[] registers = new int[6];
             * registers[0] = 1;
             * Log.WriteLine("Beginning a program of " + instructions.Count + " length. Instruction pointer is at " + ip + " register state is " + DumpRegisters(registers));
             *
             *
             * long instructionCount = 0;
             * while (true)
             * {
             *      int ipVal = registers[ip];
             *      if (ipVal < 0 || ipVal > instructions.Count)
             *      {
             *              break;
             *      }
             *
             *
             *
             *      Instruction next = instructions[ipVal];
             *      var op = _allOpCodes[next.OpCode];
             *      if (!op.Execute(next.Arguments, registers))
             *      {
             *              Log.WriteLine("Failed to execute line " + ipVal);
             *      }
             *      instructionCount++;
             *      registers[ip]++;
             *      if (ipVal == 7)
             *      {
             *              Log.WriteLine("Executed " + op.Name + " line " + ipVal + " register state is " + DumpRegisters(registers));
             *              //break;
             *      }
             * }
             *
             * /*
             * int programStartPoint = sets * 4;
             * for (int i = programStartPoint; i < allLines.Length; i++)
             * {
             *      string line = allLines[i].Trim();
             *      if (!string.IsNullOrEmpty(line))
             *      {
             *              int[] commandArgs = InstructionTestSet.ParseCommand(line);
             *              string opCode = _opCodeIds[commandArgs[0]][0];
             *              var op = _allOpCodes[opCode];
             *              if (!op.Execute(commandArgs, registers))
             *              {
             *                      Log.WriteLine("Failed to execute line " + i);
             *              }
             *      }
             * }*/
            //Log.WriteLine("Program finished, register state is " + DumpRegisters(registers) + " executed " + instructionCount);
        }