예제 #1
0
        public static int Part2Solution(long[] input)
        {
            int             paintedAtLeastOnce = 0;
            List <GridMark> gridMarks          = new List <GridMark>();
            var             currentPosition    = new GridMark(0, 0, Colors.Black);
            var             currentDirection   = Direction.Up;

            IntCodeProgram intCodeProgram = new IntCodeProgram(input);

            while (true)
            {
                if (gridMarks.Count == 0)
                {
                    currentPosition.Color = Colors.White;
                }
                else
                {
                    currentPosition.Color = GetPositionColor(currentPosition, gridMarks);
                }

                if (currentPosition.Color == Colors.Black)
                {
                    intCodeProgram.Input.Enqueue(0);
                }
                else
                {
                    intCodeProgram.Input.Enqueue(1);
                }

                var type = intCodeProgram.Run();

                if (type == Halt.Terminated)
                {
                    Print(gridMarks);
                    return(paintedAtLeastOnce);
                }

                currentPosition.Color = (Colors)intCodeProgram.Output.Dequeue();
                long directionToTurn = intCodeProgram.Output.Dequeue();

                GridMark existingMark = gridMarks.SingleOrDefault(pos => pos.X == currentPosition.X && pos.Y == currentPosition.Y);
                if (existingMark != null)
                {
                    gridMarks.Remove(existingMark);
                }
                else
                {
                    paintedAtLeastOnce++;
                }
                gridMarks.Add(new GridMark(currentPosition.X, currentPosition.Y, currentPosition.Color));

                currentDirection = SetDirection(currentDirection, directionToTurn);
                currentPosition  = SetPosition(currentPosition, currentDirection);
            }
        }
예제 #2
0
        private static Colors GetPositionColor(GridMark mark, List <GridMark> gridMarks)
        {
            var position = gridMarks.SingleOrDefault(pos => pos.X == mark.X && pos.Y == mark.Y);

            if (position != null)
            {
                return(position.Color);
            }
            else
            {
                return(Colors.Black);
            }
        }
예제 #3
0
        private static GridMark SetPosition(GridMark position, Direction direction)
        {
            switch (direction)
            {
            case Direction.Up:
                position.Y++;
                break;

            case Direction.Right:
                position.X++;
                break;

            case Direction.Down:
                position.Y--;
                break;

            case Direction.Left:
                position.X--;
                break;
            }
            return(position);
        }