Beispiel #1
0
        public static void CheckTractorBeam()
        {
            StringBuilder sb           = new StringBuilder();
            var           count        = 0;
            var           inputBuffer  = new BufferBlock <long>();
            var           outputBuffer = new BufferBlock <long>();

            for (int y = 0; y < 50; y++)
            {
                for (int x = 0; x < 50; x++)
                {
                    var vm = new IntCodeVm(programStr, inputBuffer, outputBuffer);

                    var programTask = Task.Run(() => vm.RunProgram());

                    inputBuffer.Post(x);
                    inputBuffer.Post(y);
                    var output = outputBuffer.ReceiveAsync().Result;
                    count += output == 1 ? 1 : 0;
                    sb.Append(output);
                }
                sb.AppendLine();
            }

            byte[] buffer = Encoding.ASCII.GetBytes(sb.ToString());
            Console.SetCursorPosition(0, 0);
            using (var stream = Console.OpenStandardOutput(sb.Length))
            {
                stream.Write(buffer);
            }
        }
Beispiel #2
0
        public static void JumpOMatic()
        {
            var inputBuffer    = new BufferBlock <long>();
            var outputBuffer   = new BufferBlock <long>();
            var vm             = new IntCodeVm(programStr, inputBuffer, outputBuffer);
            var runningProgram = Task.Run(() => vm.RunProgram());


            var playareaDrawer = Task.Run(async() =>
            {
                var wlk = "NOT A J\nNOT B T\nAND T J\nNOT C T\nAND T J\nAND D J\nWALK\n";
                foreach (var chr in wlk)
                {
                    inputBuffer.Post((int)chr);
                }


                char lastChar;
                var drawArea   = new List <List <char> >();
                var currentRow = new List <char>();
                drawArea.Add(currentRow);
                try
                {
                    while (true)
                    {
                        var ascii = await outputBuffer.ReceiveAsync();
                        lastChar  = (char)ascii;
                        if (lastChar == '\n')
                        {
                            if (currentRow.Count() == 0)
                            {
                                Draw(drawArea);
                                drawArea.Clear();
                            }
                            currentRow = new List <char>();
                            drawArea.Add(currentRow);
                            Draw(drawArea);
                        }
                        else
                        {
                            currentRow.Add(lastChar);
                        }
                    }
                }
                catch (InvalidOperationException ex) when(ex.Source == "System.Threading.Tasks.Dataflow")
                {
                    return;
                }
            });


            runningProgram.Wait();
            outputBuffer.Complete();
        }
Beispiel #3
0
        public static bool IsWithinBeam(int x, int y)
        {
            var inputBuffer  = new BufferBlock <long>();
            var outputBuffer = new BufferBlock <long>();
            var vm           = new IntCodeVm(programStr, inputBuffer, outputBuffer);
            var programTask  = Task.Run(() => vm.RunProgram());

            inputBuffer.Post(x);
            inputBuffer.Post(y);
            return(outputBuffer.ReceiveAsync().Result == 1 ? true : false);
        }
Beispiel #4
0
        public static int DrawPlayarea(IEnumerable <long> instructions)
        {
            var blockTileCount = 0;
            var inputBuffer    = new BufferBlock <long>();
            var outputBuffer   = new BufferBlock <long>();
            var batchBlock     = new BatchBlock <long>(3);

            outputBuffer.LinkTo(batchBlock, new DataflowLinkOptions {
                PropagateCompletion = true
            });
            var vm             = new IntCodeVm(instructions, inputBuffer, outputBuffer);
            var runningProgram = Task.Run(() => vm.RunProgram());

            var playareaDrawer = Task.Run(async() =>
            {
                var endOperation  = false;
                var outputCounter = -1;
                var xPos          = 0;
                var yPos          = 0;
                var tileMarkers   = " W#_O";

                while (!endOperation)
                {
                    try
                    {
                        outputCounter  += 1;
                        var outputValue = await batchBlock.ReceiveAsync();
                        xPos            = (int)outputValue[0];
                        yPos            = (int)outputValue[1];
                        Console.SetCursorPosition(xPos, yPos + 1);   // +1 leave 1. row free
                        var tileId = (int)outputValue[2];
                        if (tileId == 2)
                        {
                            blockTileCount += 1;
                        }
                        Console.Write(tileMarkers[tileId].ToString());
                    }
                    catch (InvalidOperationException ex) when(ex.Source == "System.Threading.Tasks.Dataflow")
                    {
                        endOperation = true;
                    }
                }
            });

            runningProgram.Wait();
            outputBuffer.Complete();
            playareaDrawer.Wait();

            return(blockTileCount);  // should be 335
        }
Beispiel #5
0
        public static void Cat6Router()
        {
            var computers     = new List <IntCodeVm>();
            var inputBuffers  = new List <BufferBlock <long> >();
            var outputBuffers = new List <BatchBlock <long> >();
            var programTasks  = new List <Task>();

            for (int i = 0; i < 50; i++)
            {
                var input = new BufferBlock <long>();
                input.Post(i);
                inputBuffers.Add(input);
                var output = new BatchBlock <long>(batchSize: 3);
                outputBuffers.Add(output);
                var vm = new IntCodeVm(i.ToString(), programStr, input, output);
                computers.Add(vm);
                programTasks.Add(Task.Run(() => vm.RunProgram()));
            }

            var routerTask = Task.Run(() =>
            {
                while (true)
                {
                    for (int i = 0; i < 50; i++)
                    {
                        if (outputBuffers[i].TryReceive(out var message))
                        {
                            var destAddr = (int)message[0];
                            if (destAddr == 255)
                            {
                                var theAnswer = message[2];
                            }
                            var input = inputBuffers[(int)message[0]];
                            input.Post(message[1]);
                            input.Post(message[2]);
                        }
                        else
                        {
                            inputBuffers[i].Post(-1);
                        }
                    }
                }
            });

            Task.WaitAll(programTasks.ToArray());
            routerTask.Wait();
        }
Beispiel #6
0
        public static void Cat6RouterWithNat()
        {
            var computers     = new List <IntCodeVm>();
            var inputBuffers  = new List <BufferBlock <long> >();
            var outputBuffers = new List <BatchBlock <long> >();
            var programTasks  = new List <Task>();

            for (int i = 0; i < 50; i++)
            {
                var input = new BufferBlock <long>();
                input.Post(i);
                inputBuffers.Add(input);
                var output = new BatchBlock <long>(batchSize: 3);
                outputBuffers.Add(output);
                var vm = new IntCodeVm(i.ToString(), programStr, input, output);
                computers.Add(vm);
                programTasks.Add(Task.Run(() => vm.RunProgram()));
            }


            var routerTask = Task.Run(() =>
            {
                (long X, long Y)messageBlock = (0, 0);
                var natHasValue = false;
                var lastY       = 0L;
                while (true)
                {
                    for (int i = 0; i < 50; i++)
                    {
                        if (outputBuffers[i].TryReceive(out var message))
                        {
                            var destAddr = (int)message[0];
                            if (destAddr == 255)
                            {
                                messageBlock.X = message[1];
                                messageBlock.Y = message[2];
                                natHasValue    = true;
                            }
                            else
                            {
                                var inputBuffer = inputBuffers[(int)message[0]];
                                inputBuffer.Post(message[1]);
                                inputBuffer.Post(message[2]);
                            }
                        }
                        else
                        {
                            if (natHasValue && inputBuffers.All(i => i.Count == 0))
                            {
                                if (lastY == messageBlock.Y)
                                {
                                    var halt = true;
                                }
                                inputBuffers[0].Post(messageBlock.X);
                                inputBuffers[0].Post(messageBlock.Y);
                                lastY       = messageBlock.Y;
                                natHasValue = false;
                            }
                            else
                            {
                                inputBuffers[i].Post(-1);
                            }
                        }
                    }
                }
            });

            Task.WaitAll(programTasks.ToArray());
            routerTask.Wait();
        }
Beispiel #7
0
        public static void Adventure()
        {
            var disableOutput      = false;
            var input              = new BufferBlock <long>();
            var output             = new BufferBlock <long>();
            var vm                 = new IntCodeVm(inputStr, input, output);
            var runningProgramTask = Task.Run(() => vm.RunProgram());
            var displayTask        = Task.Run(async() =>
            {
                var currentRow = new List <char>();
                var drawArea   = new List <List <char> >();
                while (true)
                {
                    var lastChar = (char)(await output.ReceiveAsync());
                    if (lastChar == '\n')
                    {
                        if (currentRow.Count == 0)
                        {
                            Draw(drawArea, disableOutput);
                            //drawArea.Clear();
                        }
                        currentRow = new List <char>();
                        drawArea.Add(currentRow);
                        Draw(drawArea, disableOutput);
                    }
                    else
                    {
                        currentRow.Add(lastChar);
                    }
                }
            });
            var inputTask = Task.Run(async() =>
            {
                while (true)
                {
                    if (await vm.AwaitingInputAsync() == true)
                    {
                        Console.CursorVisible = true;
                        var readLine          = Console.ReadLine();

                        if (readLine == "collect all")
                        {
                            readLine = "north\nwest\ntake mug\nwest\ntake easter egg\neast\neast\nsouth\nsouth\ntake asterisk\n" +
                                       "south\nwest\nnorth\ntake jam\nsouth\neast\nnorth\neast\ntake klein bottle\nsouth\nwest\ntake tambourine\n" +
                                       "west\ntake cake\neast\nsouth\neast\ntake polygon\nnorth";
                        }
                        else if (readLine == "drop all")
                        {
                            readLine = "drop polygon\ndrop easter egg\ndrop tambourine\ndrop asterisk\ndrop mug\ndrop jam\ndrop klein bottle\ndrop cake";
                        }
                        else if (readLine == "disable output")
                        {
                            disableOutput = true;
                        }
                        else if (readLine == "enable output")
                        {
                            disableOutput = false;
                        }
                        else if (readLine == "brute force into")
                        {
                            try
                            {
                                var items = new[] { "polygon", "easter egg", "tambourine", "asterisk", "mug", "jam", "klein bottle", "cake" };
                                var pset  = powerSet(items);

                                var sb = new StringBuilder();
                                await foreach (var set in pset)
                                {
                                    sb.Clear();
                                    sb.Append("drop all\n");
                                    foreach (var item in set)
                                    {
                                        sb.Append($"take {item}\n");
                                    }
                                    sb.Append($"east\n");
                                    readLine = sb.ToString();
                                    foreach (var character in readLine)
                                    {
                                        input.Post((int)character);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }


                        foreach (var character in readLine)
                        {
                            input.Post((int)character);
                        }
                        input.Post(10); // \n

                        Console.CursorVisible = false;
                    }
                }
            });

            runningProgramTask.Wait();
            output.Complete();
            displayTask.Wait();
            inputTask.Wait();
        }
Beispiel #8
0
        public static long AutoPlayBreakout(IEnumerable <long> instructions)
        {
            var score        = 0L;
            var inputBuffer  = new BufferBlock <long>();
            var outputBuffer = new BufferBlock <long>();
            var batchBlock   = new BatchBlock <long>(3);

            outputBuffer.LinkTo(batchBlock, new DataflowLinkOptions {
                PropagateCompletion = true
            });
            var vm             = new IntCodeVm(instructions, inputBuffer, outputBuffer);
            var runningProgram = Task.Run(() => vm.RunProgram());

            //0 is an empty tile.No game object appears in this tile.
            //1 is a wall tile.Walls are indestructible barriers.
            //2 is a block tile.Blocks can be broken by the ball.
            //3 is a horizontal paddle tile. The paddle is indestructible.
            //4 is a ball tile.The ball moves diagonally and bounces off objects.

            var playareaDrawer = Task.Run(async() =>
            {
                var endOperation  = false;
                var outputCounter = -1;
                var xPos          = 0;
                var yPos          = 0;
                var tileMarkers   = " W#_O";
                var ballXPos      = -1;
                var paddleXPos    = -1;
                while (!endOperation)
                {
                    try
                    {
                        outputCounter  += 1;
                        var outputValue = await batchBlock.ReceiveAsync();
                        xPos            = (int)outputValue[0];
                        yPos            = (int)outputValue[1];
                        if (xPos >= 0)
                        {
                            // draw play area
                            var tileId = (int)outputValue[2];
                            if (tileId == 4)
                            {
                                ballXPos = xPos;
                                //Task.Delay(1).Wait();
                                // move joystick only after paddle has been drawn
                                var joystickInput = ballXPos <paddleXPos ? -1 : ballXPos> paddleXPos ? 1 : 0;   // -1 left, 0 neutral, 1 right
                                paddleXPos       += joystickInput;
                                inputBuffer.Post(joystickInput);
                            }
                            else if (tileId == 3)
                            {
                                paddleXPos = xPos;
                            }
                            //if ((tileId == 4 || tileId == 3) && (ballXPos > -1 && paddleXPos > -1))
                            //{

                            //}

                            Console.SetCursorPosition(xPos, yPos + 1);   // +1 leave 1. row free
                            Console.Write(tileMarkers[tileId].ToString());
                        }
                        else
                        {
                            // draw score count
                            Console.SetCursorPosition(0, 0);   // +1 leave 1. row free
                            score = outputValue[2];
                            Console.Write($"Score: {score}");
                        }
                    }
                    catch (InvalidOperationException ex) when(ex.Source == "System.Threading.Tasks.Dataflow")   // Dataflow has completed and outputBuffer is empty (Program has ended it's not producing any more output)
                    {
                        endOperation = true;
                    }
                }
            });

            runningProgram.Wait();
            outputBuffer.Complete();
            playareaDrawer.Wait();

            return(score);  // should be 335
        }
Beispiel #9
0
        public static int CalibrateCamera()
        {
            var inputBuffer    = new BufferBlock <long>();
            var outputBuffer   = new BufferBlock <long>();
            var input          = programStr;
            var inputArray     = input.Split(",");
            var program        = inputArray.Select(v => long.Parse(v)).ToArray();
            var vm             = new IntCodeVm(program, inputBuffer, outputBuffer);
            var runningProgram = Task.Run(() => vm.RunProgram());

            var playareaDrawer = Task.Run(async() =>
            {
                var scaffolds  = new List <List <char> >();
                var currentRow = new List <char>();
                scaffolds.Add(currentRow);
                int x                    = 0;
                int y                    = 0;
                char lastPixel           = (char)0;
                var rowWidth             = 0;
                var cameraCalibration    = 0;
                var intersectionSequence = new[] { '#', '#', '#' };
                while (true)
                {
                    try
                    {
                        var cameraOutput = await outputBuffer.ReceiveAsync();
                        lastPixel        = (char)cameraOutput;
                        if (lastPixel == '\n')
                        {
                            currentRow = new List <char>();
                            scaffolds.Add(currentRow);
                            x        = 0;
                            y       += 1;
                            rowWidth = scaffolds[y - 1].Count();
                        }
                        else
                        {
                            currentRow.Add(lastPixel);
                            x += 1;
                        }

                        if (
                            y > 0 &&
                            x - 2 >= 0 &&
                            x + 1 < rowWidth &&
                            lastPixel == '#' &&
                            scaffolds[y - 1].ToArray()[(x - 2)..(x + 1)].SequenceEqual(intersectionSequence))
                        {
                            scaffolds[y - 1][x - 1] = 'O';
                            cameraCalibration      += (y - 1) * (x - 1);
                        }
                    }
                    catch (InvalidOperationException ex) when(ex.Source == "System.Threading.Tasks.Dataflow")
                    {
                        foreach (var row in scaffolds)
                        {
                            foreach (var item in row)
                            {
                                Debug.Write(item);
                            }
                            Debug.WriteLine("");
                        }

                        return(cameraCalibration);
                    }
                }
            });

            runningProgram.Wait();
            outputBuffer.Complete();
            return(playareaDrawer.Result);
        }
Beispiel #10
0
        internal static void WarnRobots()
        {
            var inputBuffer  = new BufferBlock <long>();
            var outputBuffer = new BufferBlock <long>();
            var vm           = new IntCodeVm(programStr, inputBuffer, outputBuffer);

            vm.Poke(0, 2);
            var runningProgram = Task.Run(() => vm.RunProgram());


            // This is cheating. Should use code to learn the sentence and then use LZ77 to compress it to 3 parts.
            var command = "A,B,A,C,B,C,A,B,A,C\nR,10,L,8,R,10,R,4\nL,6,L,6,R,10\nL,6,R,12,R,12,R,10\ny\n";

            foreach (var charVal in Encoding.ASCII.GetBytes(command))
            {
                inputBuffer.Post(charVal);
            }

            var playareaDrawer = Task.Run(async() =>
            {
                var scaffolds  = new List <List <char> >();
                var currentRow = new List <char>();
                scaffolds.Add(currentRow);
                int x                    = 0;
                int y                    = 0;
                char lastPixel           = (char)0;
                var rowWidth             = 0;
                var cameraCalibration    = 0;
                var intersectionSequence = new[] { '#', '#', '#' };
                while (true)
                {
                    try
                    {
                        var cameraOutput = await outputBuffer.ReceiveAsync();

                        if (cameraOutput > char.MaxValue)
                        {
                            var result = cameraOutput;
                        }

                        lastPixel = (char)cameraOutput;
                        if (lastPixel == '\n')
                        {
                            if (currentRow.Count() == 0)
                            {
                                Draw(scaffolds);
                                scaffolds.Clear();
                            }
                            currentRow = new List <char>();
                            scaffolds.Add(currentRow);
                            x  = 0;
                            y += 1;
                        }
                        else
                        {
                            currentRow.Add(lastPixel);
                            x += 1;
                        }
                    }
                    catch (InvalidOperationException ex) when(ex.Source == "System.Threading.Tasks.Dataflow")
                    {
                        Draw(scaffolds);

                        return;
                    }
                }
            });

            runningProgram.Wait();
            outputBuffer.Complete();
            playareaDrawer.Wait();
        }
Beispiel #11
0
        public static int CalibrateCamera()
        {
            var inputBuffer    = new BufferBlock <long>();
            var outputBuffer   = new BufferBlock <long>();
            var input          = programStr;
            var inputArray     = input.Split(",");
            var program        = inputArray.Select(v => long.Parse(v)).ToArray();
            var vm             = new IntCodeVm(program, inputBuffer, outputBuffer);
            var runningProgram = Task.Run(() => vm.RunProgram());

            var playareaDrawer = Task.Run(async() =>
            {
                var scaffolds  = new List <List <char> >();
                var currentRow = new List <char>();
                scaffolds.Add(currentRow);
                int x                    = 0;
                int y                    = 0;
                char lastPixel           = (char)0;
                var rowWidth             = 0;
                var cameraCalibration    = 0;
                var intersectionSequence = new[] { '#', '#', '#' };
                while (true)
                {
                    try
                    {
                        var cameraOutput = await outputBuffer.ReceiveAsync();
                        lastPixel        = (char)cameraOutput;
                        if (lastPixel == '\n')
                        {
                            currentRow = new List <char>();
                            scaffolds.Add(currentRow);
                            x        = 0;
                            y       += 1;
                            rowWidth = scaffolds[y - 1].Count();
                        }
                        else
                        {
                            currentRow.Add(lastPixel);
                            x += 1;
                        }

                        if (
                            y > 0 &&
                            x - 2 >= 0 &&
                            x + 1 < rowWidth &&
                            lastPixel == '#' &&
                            scaffolds[y - 1].ToArray()[(x - 2)..(x + 1)].SequenceEqual(intersectionSequence))
                        {
                            scaffolds[y - 1][x - 1] = 'O';
                            cameraCalibration      += (y - 1) * (x - 1);
                        }
                    }
                    catch (InvalidOperationException ex) when(ex.Source == "System.Threading.Tasks.Dataflow")
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int yc = 0; yc < scaffolds.Count(); yc++)
                        {
                            for (int xc = 0; xc < scaffolds[yc].Count(); xc++)
                            {
                                sb.Append(scaffolds[yc][xc]);
                            }
                            sb.AppendLine();
                        }

                        byte[] buffer = Encoding.ASCII.GetBytes(sb.ToString());
                        using (var stream = Console.OpenStandardOutput(sb.Length))
                        {
                            stream.Write(buffer);
                        }

                        return(cameraCalibration);
                    }
                }
            });

            runningProgram.Wait();
            outputBuffer.Complete();
            return(playareaDrawer.Result);
        }