Ejemplo n.º 1
0
        private int ProcessAmplifierControllerProgram(IEnumerable <int> phaseSettings)
        {
            IntcodeComputer computer = new IntcodeComputer(_rawInput);
            int             output   = 0;

            int[] inputs;
            foreach (int setting in phaseSettings)
            {
                inputs = new int[] { setting, output };
                computer.ComputeOpcodes(null, null, inputs);
                output = computer.Output[0];
            }
            return(output);
        }
Ejemplo n.º 2
0
        public static void Test1()
        {
            var intcode = new List <int>
            {
                1002,
                4,
                3,
                4,
                33
            };
            var computer = new IntcodeComputer(intcode);

            computer.Compute();
            List <int> result = computer.Memory;
        }
Ejemplo n.º 3
0
        public static void PartTwo()
        {
            long[] data = InputHelper.GetIntcodeFromFile("2");

            for (int noun = 0; noun < 100; noun++)
            {
                for (int verb = 0; verb < 100; verb++)
                {
                    IntcodeComputer i = new IntcodeComputer(data);
                    if (i.Run(noun, verb) == 19690720)
                    {
                        Console.WriteLine($"{noun} {verb}");
                        return;
                    }
                }
            }
        }
Ejemplo n.º 4
0
        private static void Part1()
        {
            var computer = new IntcodeComputer(GetIntCode(), new List <int> {
                1
            });

            computer.Compute();

            if (computer.Output.Take(computer.Output.Count - 1).Any(x => x != 0))
            {
                throw new Exception("Test Failed");
            }

            Console.WriteLine("Part 1:");
            Console.WriteLine($"Diagnostic Code: {computer.Output.Last()}");
            Console.WriteLine();
        }
Ejemplo n.º 5
0
        public static void Test2()
        {
            var intcode = new List <int>
            {
                3,
                0,
                4,
                0,
                99
            };
            var input = new List <int> {
                1
            };
            var computer = new IntcodeComputer(intcode, input);

            computer.Compute();
            List <int> result = computer.Output;
        }
Ejemplo n.º 6
0
        private static Maze MakeMaze(IntcodeComputer com)
        {
            long  output = -1;
            long  input  = 1;
            Point pos    = new Point(0, 0);
            Maze  m      = new Maze();
            int   iter   = 0;

            m.AddStartAt(0, 0);
            while (iter < 100000)
            {
                Point left = Move(TurnLeft(input), pos);
                if (!(m.CellAt(left.X, left.Y) is MazeWall))
                {
                    input = TurnLeft(input);
                }
                com.InputQueue.Enqueue(input);
                while (com.OutputQueue.Count == 0)
                {
                    ;
                }
                output = com.OutputQueue.Dequeue();
                switch (output)
                {
                case 0:
                    AddWall(input, pos, m);
                    input = TurnRight(input);
                    break;

                case 1:
                    pos = Move(input, pos);
                    AddCorridor(pos, m);
                    break;

                case 2:
                    pos = Move(input, pos);
                    AddExit(pos, m);
                    break;
                }
                iter++;
            }
            return(m);
        }
Ejemplo n.º 7
0
        public object SolvePart2()
        {
            int             targetOutput = 19690720;
            List <int>      results;
            IntcodeComputer computer = new IntcodeComputer(rawInput);

            for (int noun = 0; noun < 100; noun++)
            {
                for (int verb = 0; verb < 100; verb++)
                {
                    results = computer.ComputeOpcodes(noun, verb);
                    if (results[0] == targetOutput)
                    {
                        return((noun * 100) + verb);
                    }
                }
            }
            throw new Exception("Solution could not be found.");
        }
Ejemplo n.º 8
0
        public static void PartOne()
        {
            long[] data = InputHelper.GetIntcodeFromFile("7");

            List <int> phases = new List <int> {
                0, 1, 2, 3, 4
            };

            var allPhases = Permute(phases);
            Dictionary <long, List <int> > outputPerPhase = new Dictionary <long, List <int> >();

            foreach (IEnumerable <int> p in allPhases)
            {
                var             phase = p.ToList();
                IntcodeComputer a     = new IntcodeComputer(data);
                a.InputQueue.Enqueue(phase[0]);
                a.InputQueue.Enqueue(0);
                a.Run();
                IntcodeComputer b = new IntcodeComputer(data);
                b.InputQueue.Enqueue(phase[1]);
                b.InputQueue.Enqueue(a.OutputQueue.Dequeue());
                b.Run();
                IntcodeComputer c = new IntcodeComputer(data);
                c.InputQueue.Enqueue(phase[2]);
                c.InputQueue.Enqueue(b.OutputQueue.Dequeue());
                c.Run();
                IntcodeComputer d = new IntcodeComputer(data);
                d.InputQueue.Enqueue(phase[3]);
                d.InputQueue.Enqueue(c.OutputQueue.Dequeue());
                d.Run();
                IntcodeComputer e = new IntcodeComputer(data);
                e.InputQueue.Enqueue(phase[4]);
                e.InputQueue.Enqueue(d.OutputQueue.Dequeue());
                e.Run();
                long output = e.OutputQueue.Dequeue();
                outputPerPhase.Add(output, phase);
                Console.WriteLine($"Phase {String.Join(',', phase)} produces output {output}");
            }
            var maxPhase = outputPerPhase.First(o => o.Key == outputPerPhase.Max(k => k.Key));

            Console.WriteLine($"Phase with biggest output {String.Join(',', maxPhase.Value)} produces output {maxPhase.Key}");
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            IOutputWriter outputWriter = new ConsoleWriter();
            IInputReader  inputReader  = new ConsoleReader();


            StoryWriter     storyWriter     = new StoryWriter(outputWriter);
            UserInputReader userInputReader = new UserInputReader(inputReader, outputWriter);

            storyWriter.Title();
            storyWriter.AllDays();

            for (int input = userInputReader.GetNumericInputInclusive(MaxMenuOptions); input != MaxMenuOptions; input = userInputReader.GetNumericInputInclusive(MaxMenuOptions))
            {
                switch (input)
                {
                case 1:
                    FuelCounterUpper fuelCounterUpper = new FuelCounterUpper(outputWriter);
                    fuelCounterUpper.Initialize();
                    break;

                case 2:
                    IntcodeComputer intcodeComputer = new IntcodeComputer(outputWriter);
                    intcodeComputer.Initialize();
                    break;

                case 3:
                    FuelManager fuelManager = new FuelManager(outputWriter);
                    fuelManager.Initialize();
                    break;

                case 4:
                    VenusFuelDepot fuelDepot = new VenusFuelDepot(outputWriter);
                    fuelDepot.Initialize();
                    break;
                }

                inputReader.ReadLine();
                storyWriter.AllDays();
            }
        }
Ejemplo n.º 10
0
        public static void PartTwo()
        {
            long[] data = InputHelper.GetIntcodeFromFile("13");

            IntcodeComputer computer = new IntcodeComputer(data, IntcodeMode.Quiet | IntcodeMode.Blocking);

            computer.Context.Data[0] = 2;
            List <Tile> tiles = new List <Tile>();

            while (!computer.IsFinished)
            {
                computer.RunUntilInput();
                UpdateTiles(tiles, computer.OutputQueue.ToList().Sublists(3).Select(t => new Tile(t[0], t[1], t[2])).ToList());
                computer.OutputQueue.Clear();
                Display(tiles);
                int currentBallX = (int)tiles.First(t => t.Type == Tile.TileId.Ball).X;
                int currentPadX  = (int)tiles.First(t => t.Type == Tile.TileId.Paddle).X;
                computer.InputQueue.Enqueue(currentBallX - currentPadX);
                computer.Step();
            }
        }
Ejemplo n.º 11
0
        private static string RunBoostProgram(long input)
        {
            //Init
            var computer = new IntcodeComputer();
            var program  = File.ReadAllText(@"..\..\..\Day9Input.txt").Split(",").Select(value => long.Parse(value)).ToList();
            var result   = new List <long>();

            //Load program
            computer.Load(program);

            //Run program
            while (computer.State != ProgramState.Finished)
            {
                var output = computer.Run(new Queue <long>(new long[] { input }));
                if (output.HasValue)
                {
                    result.Add(output.Value);
                }
            }

            return(string.Join(",", result.Select(value => value.ToString())));
        }
Ejemplo n.º 12
0
        private static (int noun, int verb) FindInputs()
        {
            List <int> intcode  = GetIntCode();
            var        computer = new IntcodeComputer(intcode);

            foreach (int noun in Enumerable.Range(0, 100))
            {
                foreach (int verb in Enumerable.Range(0, 100))
                {
                    computer.Reset();
                    computer.Memory[1] = noun;
                    computer.Memory[2] = verb;
                    computer.Compute();

                    if (computer.Memory[0] == 19690720)
                    {
                        return(noun, verb);
                    }
                }
            }

            throw new Exception("No matching inputs found");
        }
Ejemplo n.º 13
0
        public static void PartOne()
        {
            long[]          data     = InputHelper.GetIntcodeFromFile("21");
            IntcodeComputer com      = new IntcodeComputer(data, IntcodeMode.Blocking | IntcodeMode.Quiet);
            List <string>   commands = new List <string>();

            Console.WriteLine("Data ?");
            string line = "";

            while (line != "WALK")
            {
                line = Console.ReadLine();
                commands.Add(line + '\n');
            }
            foreach (string command in commands)
            {
                foreach (char c in command)
                {
                    com.InputQueue.Enqueue(c);
                }
            }
            com.Run();
            if (com.OutputQueue.Count > 1)
            {
                StringBuilder sb = new StringBuilder();
                while (com.OutputQueue.Count > 0)
                {
                    long output = com.OutputQueue.Dequeue();
                    sb.Append((char)output);
                }
                Console.WriteLine(sb.ToString());
            }
            else
            {
                Console.WriteLine("Result : " + com.OutputQueue.Dequeue());
            }
        }
Ejemplo n.º 14
0
        private static void Test1()
        {
            var intCode = new List <int>
            {
                1,
                9,
                10,
                3,
                2,
                3,
                11,
                0,
                99,
                30,
                40,
                50
            };

            var computer = new IntcodeComputer(intCode);

            computer.Compute();

            List <int> result = computer.Memory;
        }
Ejemplo n.º 15
0
        public static void PartOne()
        {
            long[] data = InputHelper.GetIntcodeFromFile("19");

            StringBuilder sb = new StringBuilder();

            for (int y = 810; y < 1047; y++)
            {
                for (int x = 840; x < 1047; x++)
                {
                    IntcodeComputer com = new IntcodeComputer(data, IntcodeMode.Quiet);
                    com.InputQueue.Enqueue(x);
                    com.InputQueue.Enqueue(y);
                    com.Run();
                    if (com.OutputQueue.Dequeue() == 0)
                    {
                        sb.Append('.');
                    }
                    else
                    {
                        if (y >= 812 && x >= (845 + 84) &&
                            y < 912 && x < (945 + 84))
                        {
                            sb.Append('X');
                        }
                        else
                        {
                            sb.Append('#');
                        }
                    }
                }
                sb.AppendLine();
            }

            File.WriteAllText(InputHelper.GetOutputPathForFile("19_big_offset"), sb.ToString());
        }
Ejemplo n.º 16
0
 public Day5()
 {
     inputGetter = new InputGetter();
     rawInput    = inputGetter.GetRawString(fileName);
     computer    = new IntcodeComputer(rawInput);
 }
Ejemplo n.º 17
0
 public Day9()
 {
     _inputGetter = new InputGetter();
     _rawInput    = _inputGetter.GetRawString(_fileName);
     _computer    = new IntcodeComputer(_rawInput);
 }
Ejemplo n.º 18
0
        static async Task Main(string[] args)
        {
            //Day 1
            var rocket = await Rocket.BuildRocketFromImportedModules();

            Console.WriteLine($"Total Fuel Required By Module Mass: {rocket.CalculateTotalFuelRequiredByMass()}");
            Console.WriteLine($"Total Fuel Required: {rocket.CalculateTotalFuelRequired()}");

            //Day 2
            var intcode = await IntcodeComputer.ParseImportFileForIntCode();

            var intcodeComputer = new IntcodeComputer(intcode, 12, 2);

            Console.WriteLine($"Value at position 0: {intcodeComputer.ProcessIntcode()}");
            var foundNounAndVerb = false;

            for (int noun = 0; noun < 99; noun++)
            {
                if (foundNounAndVerb)
                {
                    break;
                }
                for (int verb = 0; verb < 99; verb++)
                {
                    if (foundNounAndVerb)
                    {
                        break;
                    }
                    var tempComputer = new IntcodeComputer(intcode, noun, verb);
                    try
                    {
                        if (tempComputer.ProcessIntcode() == 19690720)
                        {
                            Console.WriteLine($"100 * Noun + Verb: {100 * noun + verb}");
                            foundNounAndVerb = true;
                        }
                    }
                    catch (Exception)
                    {
                        //Do nothing
                    }
                }
            }

            //Day 3
            var electricalPanel = new ElectricPanel(await ElectricPanel.ParseImportFileForWirePaths());

            electricalPanel.ProcessPaths();
            var(x, y, _) = electricalPanel.FindClosesIntersectionToOriginByManhattanDistance();
            Console.WriteLine($"Manhattan Distance to closest intersection: {Math.Abs(x)+Math.Abs(y)}");
            var(_, _, z) = electricalPanel.FindClosesIntersectionToOriginByWireLength();
            Console.WriteLine($"Wire Distance to closest intersection: {z}");

            //Day 4
            var passwordCracker = new PasswordCracker(183564, 657474);
            var validPasswords  = passwordCracker.FindValidPasswords(false);

            Console.WriteLine($"Number of valid passwords with no length restriction on repeats: {validPasswords.Count}");
            validPasswords = passwordCracker.FindValidPasswords(true);
            Console.WriteLine($"Number of valid passwords with a repeat of exactly two: {validPasswords.Count}");

            //Day 5
            var intcodeDay5 = await Day05.IntcodeComputer.ParseImportFileForIntCode();

            var intcodeComputerDay5 = new Day05.IntcodeComputer(intcodeDay5, 1);

            intcodeComputerDay5.ProcessIntcode();
            intcodeComputerDay5 = new Day05.IntcodeComputer(intcodeDay5, 5);
            intcodeComputerDay5.ProcessIntcode();

            Console.ReadKey();
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            {
                int totalFuel1 = 0;
                foreach (var line in File.ReadLines("input/1.txt"))
                {
                    int mass = Int32.Parse(line);
                    int fuel = (mass / 3) - 2;
                    if (fuel > 0)
                    {
                        totalFuel1 += fuel;
                    }
                }
                Console.WriteLine($"D1P1 fuel: {totalFuel1}");
            }

            {
                int totalFuel2 = 0;
                foreach (var line in File.ReadLines("input/1.txt"))
                {
                    int mass = Int32.Parse(line);
                    int fuel = (mass / 3) - 2;
                    while (fuel > 0)
                    {
                        totalFuel2 += fuel;
                        fuel        = (fuel / 3) - 2;
                    }
                }
                Console.WriteLine($"D1P2 fuel: {totalFuel2}");
            }

            {
                var rawOpCodes = File.ReadAllText("input/2.txt");
                var opCodes    = rawOpCodes.Split(",").Select(s => Int32.Parse(s)).ToList();
                opCodes[1] = 12;
                opCodes[2] = 2;
                for (int i = 0; opCodes[i] != 99; i += 4)
                {
                    if (opCodes[i] == 1)
                    {
                        opCodes[opCodes[i + 3]] = opCodes[opCodes[i + 1]] + opCodes[opCodes[i + 2]];
                    }
                    else if (opCodes[i] == 2)
                    {
                        opCodes[opCodes[i + 3]] = opCodes[opCodes[i + 1]] * opCodes[opCodes[i + 2]];
                    }
                    else if (opCodes[i] != 99)
                    {
                        throw new Exception("");
                    }
                }
                Console.WriteLine($"D2P1: {opCodes[0]}");
            }

            {
                var rawOpCodes    = File.ReadAllText("input/2.txt");
                var opCodesSource = rawOpCodes.Split(",").Select(s => Int32.Parse(s)).ToList();

                Parallel.ForEach(Enumerable.Range(0, 99), (int noun) =>
                {
                    Parallel.ForEach(Enumerable.Range(0, 99), (int verb) =>
                    {
                        List <int> opCodes = new List <int>();
                        opCodes.AddRange(opCodesSource);

                        opCodes[1] = noun;
                        opCodes[2] = verb;
                        for (int i = 0; opCodes[i] != 99; i += 4)
                        {
                            if (opCodes[i] == 1)
                            {
                                opCodes[opCodes[i + 3]] = opCodes[opCodes[i + 1]] + opCodes[opCodes[i + 2]];
                            }
                            else if (opCodes[i] == 2)
                            {
                                opCodes[opCodes[i + 3]] = opCodes[opCodes[i + 1]] * opCodes[opCodes[i + 2]];
                            }
                            else if (opCodes[i] != 99)
                            {
                                throw new Exception("");
                            }
                        }

                        if (opCodes[0] == 19690720)
                        {
                            Console.WriteLine($"D2P2: {100 * noun + verb}");
                        }
                    });
                });
            }

            {
                var paths = File.ReadAllText("input/3.txt");
                var wires = paths.Split(new String[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Split(",").ToList()).ToList();
                if (wires.Count() != 2)
                {
                    throw new Exception();
                }

                var d = new Day3(wires[0], wires[1]);
                d.FindClosestIntersection();
                d.FindLeastSteps();
            }

            {
                int count = 0;
                Parallel.For(246540, 787419, p =>
                {
                    var password = Convert.ToString(p);
                    if (password.Length != 6)
                    {
                        throw new Exception();
                    }

                    bool bSuccess = false;
                    for (int i = 1; i < 6; ++i)
                    {
                        if (password[i] == password[i - 1])
                        {
                            bSuccess = true;
                        }
                        else if (password[i] < password[i - 1])
                        {
                            bSuccess = false;
                            break;
                        }
                    }

                    if (bSuccess)
                    {
                        Interlocked.Increment(ref count);
                    }
                });

                Console.WriteLine($"D4P1: {count}");
            }

            {
                int count = 0;
                Parallel.For(246540, 787419, p =>
                {
                    var password = Convert.ToString(p);
                    if (password.Length != 6)
                    {
                        throw new Exception();
                    }

                    bool bIncrement = true;
                    bool bPair      = false;
                    int pairCount   = 1;
                    for (int i = 1; i < 6; ++i)
                    {
                        if (password[i] < password[i - 1])
                        {
                            bIncrement = false;
                            break;
                        }

                        if (password[i] == password[i - 1])
                        {
                            ++pairCount;
                        }
                        else
                        {
                            if (pairCount == 2)
                            {
                                bPair = true;
                            }
                            pairCount = 1;
                        }
                    }

                    if (pairCount == 2)
                    {
                        bPair = true;
                    }

                    if (bPair && bIncrement)
                    {
                        Interlocked.Increment(ref count);
                    }
                });

                Console.WriteLine($"D4P2: {count}");
            }

            {
                var paths  = File.ReadAllText("input/5.txt");
                var d      = new Day5Part1(paths.Split(",").Select(i => int.Parse(i)).ToList());
                int output = d.Execute();
                Console.WriteLine($"D5P1: {output}");
            }

            {
                var paths  = File.ReadAllText("input/5.txt");
                var d      = new IntcodeComputer(paths.Split(",").Select(i => int.Parse(i)).ToList());
                int output = d.Execute(5);
                Console.WriteLine($"D5P1: {output}");
            }
        }
Ejemplo n.º 20
0
        public static void PartOne()
        {
            long[]       data          = InputHelper.GetIntcodeFromFile("11");
            List <Panel> panelsPainted = new List <Panel>();

            IntcodeComputer robot   = new IntcodeComputer(data, IntcodeMode.Blocking | IntcodeMode.Quiet);
            Thread          running = new Thread(() => robot.Run());

            running.Start();
            int       x      = 0;
            int       y      = 0;
            Direction facing = Direction.Up;

            while (!robot.IsFinished)
            {
                Panel panelAtXY = panelsPainted.FirstOrDefault(p => p.X == x && p.Y == y);
                if (panelAtXY == null)
                {
                    robot.InputQueue.Enqueue(0);
                }
                else
                {
                    robot.InputQueue.Enqueue(panelAtXY.Color == Color.White ? 1 : 0);
                }
                while (!robot.IsFinished && robot.OutputQueue.Count == 0)
                {
                    ;
                }
                if (robot.IsFinished)
                {
                    break;
                }
                long paint = robot.OutputQueue.Dequeue();
                if (paint == 1)
                {
                    if (panelAtXY != null)
                    {
                        panelAtXY.Color = Color.White;
                    }
                    else
                    {
                        panelsPainted.Add(new Panel(x, y, Color.White));
                    }
                }
                else
                {
                    if (panelAtXY != null)
                    {
                        panelAtXY.Color = Color.Black;
                    }
                    else
                    {
                        panelsPainted.Add(new Panel(x, y, Color.Black));
                    }
                }
                while (robot.OutputQueue.Count == 0)
                {
                    ;
                }
                long action = robot.OutputQueue.Dequeue();
                if (action == 1)
                {
                    facing = TurnRight(facing);
                }
                else
                {
                    facing = TurnLeft(facing);
                }
                switch (facing)
                {
                case Direction.Up:
                    y--;
                    break;

                case Direction.Left:
                    x--;
                    break;

                case Direction.Down:
                    y++;
                    break;

                case Direction.Right:
                    x++;
                    break;
                }
            }
            Console.WriteLine("Robot finished painting !");
            for (y = panelsPainted.Min(p => p.Y); y < panelsPainted.Max(p => p.Y); y++)
            {
                for (x = panelsPainted.Min(p => p.X); x < panelsPainted.Max(p => p.X); x++)
                {
                    Panel panelAtXY = panelsPainted.FirstOrDefault(p => p.X == x && p.Y == y);
                    if (panelAtXY == null || panelAtXY.Color == Color.Black)
                    {
                        Console.Write('.');
                    }
                    else
                    {
                        Console.Write('#');
                    }
                }
                Console.WriteLine();
            }
            Console.WriteLine($"{panelsPainted.Count} panels were painted !");
        }