Exemple #1
0
    private long RunCode(List <long> code, long valueAt1, long valueAt2)
    {
        var computer = new IntCode(code);

        if (valueAt1 >= 0)
        {
            computer.Poke(1, valueAt1);
        }
        if (valueAt2 >= 0)
        {
            computer.Poke(2, valueAt2);
        }
        computer.Run();

        var valAt0 = computer.Peek(0);

        return(valAt0);
    }
Exemple #2
0
        object PartOne(string input)
        {
            var vm = new IntCode(input);

            vm.RunToNextInputOrFinished();
            var i     = 0;
            var items = new Dictionary <Point, int>();

            while (i < vm.AllOutputs.Count)
            {
                var x    = (int)vm.AllOutputs[i++];
                var y    = (int)vm.AllOutputs[i++];
                var type = (int)vm.AllOutputs[i++];
                items[new Point(x, y)] = type;
            }

            return(items.Count(kvp => kvp.Value == 2));
        }
Exemple #3
0
        protected override object SolvePartOne()
        {
            IntCode cpu    = IntCode.Create(Input.SplitByNewline().First());
            int     i      = 0;
            int     blocks = 0;

            cpu.Output += (s, e) =>
            {
                if (i == 2 && e == 2)
                {
                    blocks++;
                }

                i = ++i % 3;
            };
            cpu.Run();
            return(blocks.ToString());
        }
Exemple #4
0
        object PartOne(string input)
        {
            var affectedSquares = 0L;

            foreach (var y in Enumerable.Range(0, 50))
            {
                foreach (var x in Enumerable.Range(0, 50))
                {
                    var vm = new IntCode(input);
                    vm.ProvideInput(x);
                    vm.ProvideInput(y);
                    var result = vm.RunToNextInputOrFinishedCollectOutput();
                    affectedSquares += result[result.Length - 1];
                }
            }

            return(affectedSquares);
        }
Exemple #5
0
        long PlayGame()
        {
            var intCode      = new IntCode(4096);
            var instructions = Instructions.ToList();

            instructions[0] = 2;

            var score = 0L;

            while (true)
            {
                if (intCode.IsPaused)
                {
                    intCode.Resume();
                }
                else
                {
                    intCode.Execute(instructions);
                }

                var tiles = GetTiles(intCode.Outputs.ToList());
                intCode.ClearOutput();

                var paddle    = (Tile?)tiles.FirstOrDefault(x => x.TileType == TileType.Paddle);
                var ball      = (Tile?)tiles.FirstOrDefault(x => x.TileType == TileType.Ball);
                var scoreInfo = (Tile?)tiles.FirstOrDefault(x => x.IsScore);
                if (scoreInfo.HasValue)
                {
                    score = scoreInfo.Value.Score;
                }

                if (!intCode.IsPaused)
                {
                    break;
                }

                var nextInput = paddle.HasValue && ball.HasValue
                    ? GetInput(paddle.Value, ball.Value) : 0;

                intCode.SetInputs(nextInput);
            }

            return(score);
        }
Exemple #6
0
    string RunPart1(InputAnswer puzzleData)
    {
        var phaseValues = new long[] { 0, 1, 2, 3, 4 };
        var answer      = 0L;

        foreach (var phase in GetPhases(phaseValues, puzzleData.Phase))
        {
            var ampA = new IntCode(puzzleData.Code);
            var ampB = new IntCode(puzzleData.Code);
            var ampC = new IntCode(puzzleData.Code);
            var ampD = new IntCode(puzzleData.Code);
            var ampE = new IntCode(puzzleData.Code);

            var outputValue = 0L;

            ampA.Output += (s, e) => outputValue = e.OutputValue;
            ampB.Output += (s, e) => outputValue = e.OutputValue;
            ampC.Output += (s, e) => outputValue = e.OutputValue;
            ampD.Output += (s, e) => outputValue = e.OutputValue;
            ampE.Output += (s, e) => outputValue = e.OutputValue;

            ampA.AddInput(phase[0], outputValue);
            ampA.Run();

            ampB.AddInput(phase[1], outputValue);
            ampB.Run();

            ampC.AddInput(phase[2], outputValue);
            ampC.Run();

            ampD.AddInput(phase[3], outputValue);
            ampD.Run();

            ampE.AddInput(phase[4], outputValue);
            ampE.Run();

            if (outputValue > answer)
            {
                answer = outputValue;
            }
        }

        return(Helper.GetPuzzleResultText($"Highest signal that can be sent to the thrusters: {answer}", answer, puzzleData.ExpectedAnswer));
    }
Exemple #7
0
        object PartTwo(string input)
        {
            var ampSettings = Enumerable.Range(5, 5).Permutate();
            var maxOutput   = long.MinValue;

            foreach (var ampSetting in ampSettings)
            {
                // Need to run all 5 computers, entering the output from each one
                // into the input of the next, until they stop.
                var computers = new IntCode[5];
                for (var index = 0; index < 5; index++)
                {
                    computers[index] = new IntCode(input);
                    computers[index].ProvideInput(ampSetting[index]);
                }

                computers[0].ProvideInput(0);

                // Run each computer until it is either finished or it is waiting for input
                int          computerRunning = -1;
                ProgramState state           = ProgramState.Running;
                do
                {
                    computerRunning = ++computerRunning % 5;
                    var currentComputer = computers[computerRunning];

                    // Provide the input to the computer.
                    var previousComputer = computers[(computerRunning + 4) % 5];
                    if (previousComputer.HasOutput)
                    {
                        currentComputer.ProvideInput(previousComputer.ReadOutput());
                    }
                    do
                    {
                        state = currentComputer.ExecuteInstruction();
                    }while(state != ProgramState.WaitingForInput && state != ProgramState.Finished);
                }while(computers[4].State != ProgramState.Finished);

                maxOutput = Math.Max(maxOutput, computers[4].AllOutputs.Last());
            }

            return(maxOutput);
        }
Exemple #8
0
        object PartOne(string input)
        {
            //var vm = new IntCode(input);
            //var currentPos = new Point(0, 0);
            //var currentStatus = Status.Empty;
            //var map = new Dictionary<Point, Status>();
            ////var wayBack = new Dictionary<Point, Direction>();
            //var shortestDistance = new Dictionary<Point, int>();
            //shortestDistance[currentPos] = 0;
            //map[currentPos] = currentStatus;
            //var pointsToCheck = new Stack<Point>();
            //pointsToCheck.Push(currentPos);

            //var g = new QuickGraph.BidirectionalGraph<Point, Edge<Point>>();
            //g.AddVertex(currentPos);

            //FloodFill(vm, currentPos, shortestDistance, map, g);

            //var system = map.First(kvp => kvp.Value == Status.System).Key;
            //return shortestDistance[system];

            var vm            = new IntCode(input);
            var currentPos    = new Point(0, 0);
            var currentStatus = Status.Empty;
            var map           = new Dictionary <Point, Status>();

            map[currentPos] = currentStatus;
            var pointsToCheck = new Stack <Point>();

            pointsToCheck.Push(currentPos);

            var g = new BidirectionalGraph <Point, Edge <Point> >();

            g.AddVertex(currentPos);

            FloodFill(vm, ref currentPos, map, g);

            var systemPoint = map.First(kvp => kvp.Value == Status.System).Key;

            g.ShortestPathsDijkstra(e => 1, new Point(0, 0))(systemPoint, out var path);
            return(path.Count());
        }
Exemple #9
0
        public void Part2()
        {
            List <long> outputs = new List <long>(3);
            long        score   = 0;
            long        ballX   = 0;
            long        paddleX = 0;

            IntCodeBase.OutputWriter writer = output =>
            {
                outputs.Add(output);
                if (outputs.Count == 3)
                {
                    if (outputs[0] == -1 && outputs[1] == 0)
                    {
                        score = outputs[2];
                    }
                    else
                    {
                        Tile tile = (Tile)outputs[2];
                        long x    = outputs[0];
                        if (tile == Tile.Ball)
                        {
                            ballX = x;
                        }
                        if (tile == Tile.Paddle)
                        {
                            paddleX = x;
                        }
                    }
                    outputs.Clear();
                }
            };

            IntCode.InputReader reader = () => Math.Sign(ballX - paddleX);

            IntCode arcade = new IntCode(_program, reader, writer);

            arcade[0] = 2;
            arcade.Run();

            Assert.Equal(8942, score);
        }
 public static void SolvePartTwo()
 {
     for (int a = 0; a < 99; a++)
     {
         for (int b = 0; b < 99; b++)
         {
             input = new List <int>();
             TakeInput();
             input[1] = a;
             input[2] = b;
             if (IntCode.CalculateOpcode(input) != 19690720)
             {
                 continue;
             }
             Console.WriteLine("a: " + a + " b: " + b);
             Console.WriteLine((100 * a) + b);
             return;
         }
     }
 }
        int CheckThrustersByFeedbackLoop(string signalPhase)
        {
            var intCodes = new IntCode[signalPhase.Length];
            var output   = 0;
            var index    = 0;

            while (true)
            {
                if (intCodes[index] == null)
                {
                    intCodes[index] = new IntCode();
                }

                var signal  = int.Parse(signalPhase[index].ToString());
                var intCode = intCodes[index];

                if (intCode.IsPaused)
                {
                    intCode.SetInputs(output);
                    intCode.Resume();
                }
                else
                {
                    intCode.SetInputs(signal, output);
                    intCode.Execute(Instructions);
                }

                output = (int)intCode.Outputs.Last();

                if (intCodes.Where(x => x != null).All(x => !x.IsPaused))
                {
                    break;
                }
                else
                {
                    index = (++index) % signalPhase.Length;
                }
            }

            return(output);
        }
Exemple #12
0
    string RunPart1(InputAnswer puzzleData, long inputValue, long?overrideExpectedAnswer = null)
    {
        if (overrideExpectedAnswer.HasValue)
        {
            puzzleData.ExpectedAnswer = overrideExpectedAnswer.Value;
        }

        var answer   = 0L;
        var computer = new IntCode(puzzleData.Code);

        computer.Output += (s, e) => { answer = e.OutputValue; };

        computer.Run();
        if (computer.State == IntCodeState.NeedsInput)
        {
            computer.AddInput(inputValue);
            computer.Run();
        }

        return(Helper.GetPuzzleResultText($"The diagnostic Code is: {answer}", answer, puzzleData.ExpectedAnswer));
    }
Exemple #13
0
        private long RunAmplifiers(IEnumerable <long> code, IEnumerable <int> phaseSettings)
        {
            long answer = 0;

            Stack <long> inputs = new Stack <long>();

            inputs.Push(0);
            foreach (int phaseSetting in phaseSettings)
            {
                inputs.Push(phaseSetting);
                IntCode amp = new IntCode(
                    code,
                    inputs.Pop,
                    value => answer = value
                    );
                amp.Run();
                inputs.Push(answer);
            }

            return(answer);
        }
Exemple #14
0
        object PartOne(string input)
        {
            var ampSettings = Enumerable.Range(0, 5).Permutate();
            var maxOutput   = long.MinValue;

            foreach (var ampSetting in ampSettings)
            {
                var ampInput = new long[5 + 1];
                for (var index = 0; index < 5; index++)
                {
                    var comp = new IntCode(input);
                    comp.ProvideInput(ampSetting[index]);
                    comp.ProvideInput(ampInput[index]);
                    comp.Run();
                    ampInput[index + 1] = comp.ReadOutput();
                }

                maxOutput = Math.Max(maxOutput, ampInput[5]);
            }

            return(maxOutput);
        }
Exemple #15
0
        private string Run(string input)
        {
            int           index   = 0;
            StringBuilder sb      = new StringBuilder();
            IntCode       intCode = new IntCode(
                _program,
                () => input[index++],
                val =>
            {
                if (val >= 0 && val <= 127)
                {
                    sb.Append((char)val);
                }
                else
                {
                    sb.Append(val.ToString());
                }
            });

            intCode.Run();
            return(sb.ToString());
        }
Exemple #16
0
        protected override object SolvePartTwo()
        {
            IntCode cpu = IntCode.Create(Input.Trim('\n'));

            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    cpu.Reset();
                    cpu.ByteCode[1] = i;
                    cpu.ByteCode[2] = j;
                    cpu.Run();

                    if (cpu.ByteCode[0] == 19690720)
                    {
                        return($"100 * {i} + {j} = {100 * i + j}");
                    }
                }
            }

            return(null);
        }
Exemple #17
0
        public Day17()
        {
            StringBuilder sb      = new StringBuilder();
            IntCode       intCode = new IntCode(
                _program,
                null,
                value =>
            {
                if (value == 10)
                {
                    sb.AppendLine();
                }
                else
                {
                    sb.Append((char)value);
                }
            });

            intCode.Run();

            _map = sb.ToString().Split().Where(s => s != string.Empty).ToArray();
        }
Exemple #18
0
        public void Part2()
        {
            const int target = 19690720;

            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    IntCode intCode = new IntCode(_program);
                    intCode[1] = i;
                    intCode[2] = j;
                    intCode.Run();

                    if (intCode[0] == target)
                    {
                        int answer = 100 * i + j;
                        Assert.Equal(6979, answer);
                        return;
                    }
                }
            }
        }
Exemple #19
0
    string RunPart2Example3(long inputValue)
    {
        var sb        = new StringBuilder();
        var inputList = InputHelper.LoadInputFile(5, "example3")
                        .Select(l => l.Split(',').Select(v => v.ToInt64()).ToList());

        sb.AppendLine($"Input: {inputValue}");
        foreach (var input in inputList)
        {
            var computer = new IntCode(input);
            computer.Output += (s, e) => sb.AppendLine($"Output: {e.OutputValue}");

            computer.Run();
            if (computer.State == IntCodeState.NeedsInput)
            {
                computer.AddInput(inputValue);
                computer.Run();
            }
        }
        sb.AppendLine();

        return(sb.ToString());
    }
Exemple #20
0
        public void Part2()
        {
            _intCodeOutput.Clear();

            FindFunctions();
            _intCodeInput = new Queue <long>();

            QueueInput(_mainRoutine);
            QueueInput(_functionA);
            QueueInput(_functionB);
            QueueInput(_functionC);
            _intCodeInput.Enqueue('n');
            _intCodeInput.Enqueue(10);

            _code[0] = 2;
            IntCode intCode = new IntCode("Day17", _code, IntCodeInput, IntCodeOutput);

            intCode.RunIntCode();

            long rslt = _intCodeOutput[_intCodeOutput.Count - 1];

            Console.WriteLine("Part2: {0}", rslt);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Day 23");
            Console.WriteLine("Star 1");
            Console.WriteLine();

            long[] regs = File.ReadAllText(inputFile).Split(',').Select(long.Parse).ToArray();

            IntCode machine = new IntCode(
                name: "Star 1",
                regs: regs,
                fixedInputs: Array.Empty <long>(),
                output: x => Console.Write(x));

            machine.SyncRun();

            int output1 = 0;



            Console.WriteLine($"The answer is: {output1}");

            Console.WriteLine();
            Console.WriteLine("Star 2");
            Console.WriteLine();


            int output2 = 0;



            Console.WriteLine($"The answer is: {output2}");


            Console.WriteLine();
            Console.ReadKey();
        }
Exemple #22
0
        protected override object SolvePartOne()
        {
            var panels = new Dictionary <Point, long>();

            (Point location, Point direction) = (new Point(), Point.North);
            IntCode cpu = IntCode.Create(Input.SplitByNewline().First());

            cpu.GetInput = (i) =>
            {
                return(panels.TryGetValue(location, out var result)
                ? result
                : 0);
            };
            int output = 0;

            cpu.Output += (s, e) =>
            {
                if (output == 0)
                {
                    panels[location] = e;
                }
                else
                {
                    direction = e switch
                    {
                        0 => new Point(direction.Y, -direction.X),
                        1 => new Point(-direction.Y, direction.X),
                        _ => throw new System.Exception(),
                    };
                    location += direction;
                }
                output = (output + 1) & 1;
            };
            cpu.Run();
            return(panels.Count.ToString());
        }
        static void TryTreeMethod(long[] regs)
        {
            // Ineffective Tree solution left for Posterity's sake
            var sw = System.Diagnostics.Stopwatch.StartNew();

            MoveTree moveTree = new MoveTree();

            while (true)
            {
                tileMap.Clear();
                inputStage = 0;

                IntCode machine2 = new IntCode(
                    name: "Star 2",
                    regs: regs,
                    fixedInputs: Array.Empty <long>(),
                    input: moveTree.NextMove,
                    output: RenderOutput1);

                machine2[0] = 2;

                machine2.SyncRun();

                if (tileMap.Values.Where(x => x == 2).Count() == 0)
                {
                    break;
                }
                else
                {
                    moveTree.MarkFailure();
                }
            }
            sw.Stop();
            Console.WriteLine($"Tree Solution took: {sw.Elapsed}");
            Console.WriteLine($"The answer is: {score}");
        }
Exemple #24
0
        public void Part1()
        {
            int         countBlocks = 0;
            List <long> outputs     = new List <long>(3);
            IntCode     arcade      = new IntCode(
                _program,
                null,
                output =>
            {
                outputs.Add(output);
                if (outputs.Count == 3)
                {
                    if ((Tile)outputs[2] == Tile.Block)
                    {
                        countBlocks++;
                    }
                    outputs.Clear();
                }
            });

            arcade.Run();

            Assert.Equal(173, countBlocks);
        }
Exemple #25
0
        private static int FindMatch(long[] initialRegs)
        {
            for (int noun = 0; noun < 100; noun++)
            {
                for (int verb = 0; verb < 100; verb++)
                {
                    IntCode intCode = new IntCode(
                        name: $"Star 2 Machine ({noun},{verb})",
                        regs: initialRegs);

                    intCode[1] = noun;
                    intCode[2] = verb;

                    intCode.Run().Wait();

                    if (intCode[0] == 19690720)
                    {
                        return(100 * noun + verb);
                    }
                }
            }

            throw new Exception("Result not found");
        }
Exemple #26
0
        private void MoveTo(Point target, ref Point currentPos, BidirectionalGraph <Point, Edge <Point> > g, IntCode vm, string because)
        {
            if (target == currentPos)
            {
                return;
            }

            var startingPoint = currentPos;
            var tryFunc       = g.ShortestPathsDijkstra(e => 1, currentPos);

            if (!tryFunc(target, out var path))
            {
                throw new Exception($"Unable to find path between {currentPos} and {target}.");
            }

            foreach (var edge in path)
            {
                var direction = edge.Source.GetDirectionTo(edge.Target);
                if (Move(ref currentPos, direction, vm, because) == Status.Wall)
                {
                    throw new Exception("Simulation is wrong somewhere.");
                }
            }
        }
Exemple #27
0
        public static void Day7Main(string inputFile)
        {
            string[] opCodeList  = System.IO.File.ReadAllText(inputFile).Split(",");
            string   currOpCode  = "";
            decimal  currIndexer = 0;
            int      opCodeCheck = 0;

            List <decimal> input_list = new List <decimal>();
            List <decimal> opCode     = new List <decimal>();

            List <List <char> > phaseListInput = new List <List <char> >();
            string str = "56789";

            char[] arr = str.ToCharArray();
            phaseListInput = GetPer(phaseListInput, arr);

            foreach (string tempOpCode in opCodeList)
            {
                opCode.Add(int.Parse(tempOpCode));
            }

            float          maxOutput     = 0;
            List <decimal> input         = new List <decimal>();
            List <char>    maxPhaseInput = new List <char>();

            //List<char> currPhaseList = new List<char> { '4', '3', '2', '1', '0' };
            //List<char> currPhaseList = new List<char> { '0', '1', '2', '3', '4' };
            //List<char> currPhaseList = new List<char> { '1', '0', '4', '3', '2' };
            //List<char> currPhaseList = new List<char> { '9', '8', '7', '6', '5' };
            //List<char> currPhaseList = new List<char> { '9', '7', '8', '5', '6' };

            List <IntCode> ampList = new List <IntCode>();

            foreach (List <char> currPhaseList in phaseListInput)
            {
                // Initialise IntCode setup
                ampList = new List <IntCode>();

                // initialise each input with its phase setting. If it's the first input, tack a 0 on (very first input = 0!)
                foreach (char currPhase in currPhaseList)
                {
                    input = new List <decimal>();
                    input.Add((int)Char.GetNumericValue(currPhase));
                    if (currPhase.Equals(currPhaseList[0]))
                    {
                        input.Add(0);
                    }
                    //Make our ampList of 5x amplifiers.
                    ampList.Add(new IntCode(new List <decimal>(opCode), input));
                }
                while (true)
                {
                    for (int i = 0; i < ampList.Count; i++)
                    {
                        IntCode currIntCode = ampList[i];
                        while (true)
                        {
                            currIndexer = currIntCode.CurrIndex;
                            currOpCode  = currIntCode.OpCode[(int)currIndexer].ToString().PadLeft(5, '0');
                            opCodeCheck = Int32.Parse(currOpCode.Substring(3, 2));
                            if (opCodeCheck == 99)
                            {
                                break;
                            }
                            else if (opCodeCheck == 3 && currIntCode.Input.Count < 1)
                            {
                                //Add output to next IntCode's input list
                                //Console.WriteLine("Input 3 and no valid input. Better keep going or I might die inside.");
                                break;
                            }
                            else
                            {
                                currIntCode = IntCode.OpCodeForward(currIntCode);
                            }
                        }
                        //we have escaped this intcode, save it!
                        ampList[i] = currIntCode;
                        if (i < (ampList.Count - 1))
                        {
                            // If it's not our last input, make the output part of our next input :)
                            ampList[i + 1].Input.Add(currIntCode.Output);
                        }
                    }

                    // Will only get here on final amplifier
                    if (opCodeCheck == 99)
                    {
                        // If we're done, let's check if our final output is the best ever
                        if ((int)ampList.Last().Output > maxOutput)
                        {
                            maxOutput     = (int)ampList.Last().Output;
                            maxPhaseInput = new List <char>(currPhaseList);
                        }
                        break;
                    }
                    else
                    {
                        ampList[0].Input.Add(ampList.Last().Output);
                    }
                }
            }

            Console.WriteLine("Final Input List is " + string.Join(",", maxPhaseInput));
            Console.WriteLine("Maximum Output is " + maxOutput);
            Console.ReadLine();
        }
Exemple #28
0
        static void Main(string[] args)
        {
            Console.WriteLine("Day 17 - Set and Forget");
            Console.WriteLine("Star 1");
            Console.WriteLine();

            long[] regs = File.ReadAllText(inputFile).Split(',').Select(long.Parse).ToArray();

            StringBuilder builder = new StringBuilder();

            IntCode machine = new IntCode(
                name: "Star 1",
                regs: regs,
                fixedInputs: Array.Empty <long>(),
                output: x => builder.Append((char)x));

            machine.SyncRun();
            string text = builder.ToString();

            string[] lines = text.Split('\n').Where(x => x.Length != 0).ToArray();

            int alignmentParam = 0;

            for (int y = 1; y < lines.Length - 1; y++)
            {
                for (int x = 1; x < lines[0].Length - 1; x++)
                {
                    if (lines[y][x] == '#')
                    {
                        if (lines[y - 1][x] == '#' && lines[y + 1][x] == '#' && lines[y][x + 1] == '#' && lines[y][x - 1] == '#')
                        {
                            alignmentParam += x * y;
                        }
                    }
                }
            }

            Console.WriteLine($"The answer is: {alignmentParam}");


            Console.WriteLine();
            Console.WriteLine("Star 2");
            Console.WriteLine();

            HashSet <Point2D> scaffold      = new HashSet <Point2D>();
            Point2D           startingPoint = Point2D.Zero;

            for (int y = 0; y < lines.Length; y++)
            {
                for (int x = 0; x < lines[0].Length; x++)
                {
                    if (lines[y][x] == '#')
                    {
                        scaffold.Add((x, y));
                    }
                    else if (lines[y][x] == '^')
                    {
                        startingPoint = (x, y);
                    }
                }
            }

            List <string> path = GetPath(startingPoint, scaffold);

            var compressed = Compress(path);

            IEnumerable <long> input =
                compressed.Seq.Select(x => (long)x).Append(10)
                .Concat(compressed.A.Select(x => (long)x)).Append(10)
                .Concat(compressed.B.Select(x => (long)x)).Append(10)
                .Concat(compressed.C.Select(x => (long)x)).Append(10)
                .Append((long)'n').Append(10);

            regs[0] = 2;

            long dust = 0;

            IntCode machine2 = new IntCode(
                name: "Star 2",
                regs: regs,
                fixedInputs: input,
                output: x => dust = x);

            machine2.SyncRun();

            Console.WriteLine($"Dust collected: {dust}");

            Console.WriteLine();
            Console.ReadKey();
        }
Exemple #29
0
        private void FloodFill(IntCode vm, ref Point currentPos, Dictionary <Point, Status> map, BidirectionalGraph <Point, Edge <Point> > g)
        {
            // Check all directions from this point.
            var pointsToCheck = new Stack <Point>();

            pointsToCheck.Push(currentPos);

            var pointStatus = new Dictionary <Direction, Status>();

            while (pointsToCheck.Count > 0)
            {
                var pointToCheck = pointsToCheck.Pop();
                Log(string.Empty);
                Log($"Checking new point {pointToCheck}");
                MoveTo(pointToCheck, ref currentPos, g, vm, $"new point to check {pointToCheck}");

                var dirsToCheck = Enum.GetValues(typeof(Direction)).Cast <Direction>();
                pointStatus.Clear();
                foreach (var dir in dirsToCheck)
                {
                    var targetPos = currentPos.GetLocation(dir);
                    if (map.ContainsKey(targetPos))
                    {
                        continue;
                    }

                    var currentStatus = Move(ref currentPos, dir, vm, $"checking out unknown position.");
                    pointStatus.Add(dir, currentStatus);
                    map[targetPos] = currentStatus;
                    switch (currentStatus)
                    {
                    case Status.Wall:
                        // The robot did not move, but it hit a wall.
                        break;

                    case Status.Empty:
                        // We moved, and are now at the target position
                        if (!g.ContainsVertex(targetPos))
                        {
                            g.AddVertex(targetPos);
                        }

                        g.AddEdge(new Edge <Point>(pointToCheck, targetPos));
                        g.AddEdge(new Edge <Point>(targetPos, pointToCheck));

                        // Add it as a point to check.
                        pointsToCheck.Push(targetPos);

                        // Then go back to the pointToCheck.
                        MoveTo(pointToCheck, ref currentPos, g, vm, $"point checked. Moving back to {pointToCheck}");

                        break;

                    case Status.System:
                        // We moved, and are now at the target position
                        if (!g.ContainsVertex(targetPos))
                        {
                            g.AddVertex(targetPos);
                        }

                        // We found the oxygen system. No need to check any further in this path. (No other way will be shorter than this).
                        // We just go back to the current position.

                        g.AddEdge(new Edge <Point>(pointToCheck, targetPos));
                        g.AddEdge(new Edge <Point>(targetPos, pointToCheck));

                        MoveTo(pointToCheck, ref currentPos, g, vm, $"point checked (System found). Moving back to {pointToCheck}");

                        break;
                    }
                }

                Log($"Finished with {pointToCheck}:");
                foreach (var kvp in pointStatus)
                {
                    Log($"  {kvp.Key}: {kvp.Value}");
                }
            }
        }
Exemple #30
0
 public Challenge()
 {
     _intCode = new IntCode();
     _intCode.Load(inputList[0]);
 }