Exemplo n.º 1
0
        private IRoverPosition Move(IRoverPosition starPosition)
        {
            IRoverPosition endPosition = new RoverPosition()
            {
                Direction = starPosition.Direction, X = starPosition.X, Y = starPosition.Y
            };

            if (endPosition.Direction == Directions.North)
            {
                endPosition.Y += 1;
            }

            if (endPosition.Direction == Directions.South)
            {
                endPosition.Y -= 1;
            }

            if (endPosition.Direction == Directions.East)
            {
                endPosition.X += 1;
            }

            if (endPosition.Direction == Directions.West)
            {
                endPosition.X -= 1;
            }

            ValidateRover(starPosition, endPosition);

            starPosition = endPosition;

            return(starPosition);
        }
Exemplo n.º 2
0
        public List <string> Command(string[] commandList)
        {
            if (commandList.Length >= 3 && commandList.Length % 2 == 1)
            {
                var moveHelper           = new MoveHelper();
                var roverPositionList    = new List <RoverPosition>();
                var expectedPositionList = new List <string>();
                var areaOfRover          = CreateRoverArea(commandList[0]);

                RoverPosition firstPosition = null;
                for (int i = 1; i < commandList.Length; i++)
                {
                    var modeOfCommand = (i - 1) % 2;
                    if (modeOfCommand == 0)
                    {
                        firstPosition = RoverLocation(commandList[i], areaOfRover);
                    }
                    else
                    {
                        roverPositionList.Add(moveHelper.RoverMove(commandList[i], firstPosition, commandList[0]));
                    }
                }

                foreach (var roverPosition in roverPositionList)
                {
                    string roverDirection = DirectionConvertToString(roverPosition.Direction);
                    expectedPositionList.Add($"{roverPosition.Coordinate.X} {roverPosition.Coordinate.Y} {roverDirection}");
                }
                return(expectedPositionList);
            }
            else
            {
                throw new ArgumentException("Invalid character for command");
            }
        }
Exemplo n.º 3
0
        public static RoverPosition TurnRight(RoverPosition pos)
        {
            switch (pos.Facing)
            {
            case 'N':
                pos.Facing = 'E';
                break;

            case 'S':
                pos.Facing = 'W';
                break;

            case 'W':
                pos.Facing = 'N';
                break;

            case 'E':
                pos.Facing = 'S';
                break;

            default:
                break;
            }
            return(pos);
        }
Exemplo n.º 4
0
        public Rover CreateRover(string positionCommand, string instructionCommand)
        {
            try
            {
                var positionList = positionCommand.Split(" ");

                ValidateRoverPosition(positionList);

                var orientation = positionList[2];
                if (!int.TryParse(positionList[0], out int x) || !int.TryParse(positionList[1], out int y))
                {
                    _logger.LogError("Rover position is not valid.");
                    throw new ArgumentException();
                }

                var position = new RoverPosition
                {
                    X = x,
                    Y = y,
                    OrientationValue = orientation
                };
                return(new Rover
                {
                    InstructionCommand = instructionCommand,
                    StartPosition = position,
                    LastPosition = position
                });
            }
            catch (Exception ex)
            {
                _logger.LogError("Error when create Rover: ");
                throw ex;
            }
        }
Exemplo n.º 5
0
        public RoverPosition RoverMove(string command, RoverPosition firstPosition, string maxLocation)
        {
            var roverLocation = new RoverPosition();
            var rgx           = new Regex("^[LRM]+$");

            if (rgx.IsMatch(command))
            {
                foreach (var item in command)
                {
                    switch (item)
                    {
                    case 'L':
                        roverLocation = LeftMove(firstPosition);
                        break;

                    case 'R':
                        roverLocation = RightMove(firstPosition);
                        break;

                    case 'M':
                        roverLocation = MidMove(firstPosition, maxLocation);
                        break;
                    }
                }
            }
            else
            {
                throw new ArgumentException($"Invalid character for move value");
            }
            return(roverLocation);
        }
Exemplo n.º 6
0
        public IEnumerable <RoverPosition> Get()
        {
            // Initialize the environment
            _environmentService.MaxX = 5;
            _environmentService.MaxY = 5;

            try
            {
                // Test1
                var start = new RoverPosition()
                {
                    Name = "Rover1", Direction = 'N', X = 1, Y = 2
                };
                string command = "LMLMLMLMM";
                // 1 3 N
                var end1 = _roverService.Navigate(start, command);
                // Test2
                start = new RoverPosition()
                {
                    Name = "Rover2", Direction = 'E', X = 3, Y = 3
                };
                command = "MMRMMRMRRM";
                // 5 1 E
                var end2 = _roverService.Navigate(start, command);

                return(new RoverPosition[] { end1, end2 });
            }
            catch
            { }

            return(null);
        }
Exemplo n.º 7
0
        private RoverPosition TurnRight(RoverPosition start)
        {
            switch (start.Direction)
            {
            case 'E':
                start.Direction = 'S';
                break;

            case 'S':
                start.Direction = 'W';
                break;

            case 'W':
                start.Direction = 'N';
                break;

            case 'N':
                start.Direction = 'E';
                break;

            default:
                break;
            }
            return(start);
        }
Exemplo n.º 8
0
        public RoverPosition MidMove(RoverPosition roverPosition, string maxLocation)
        {
            var maxCoordinate  = maxLocation.Split(' ');
            var maxCoordinateX = Convert.ToInt32(maxCoordinate[0]);
            var maxCoordinateY = Convert.ToInt32(maxCoordinate[1]);

            if (roverPosition.Coordinate.X <= maxCoordinateX && roverPosition.Coordinate.Y <= maxCoordinateY)
            {
                switch (roverPosition.Direction)
                {
                case DirectionType.North:
                    roverPosition.Coordinate.Y++;
                    break;

                case DirectionType.South:
                    roverPosition.Coordinate.Y--;
                    break;

                case DirectionType.East:
                    roverPosition.Coordinate.X++;
                    break;

                case DirectionType.West:
                    roverPosition.Coordinate.X--;
                    break;
                }
            }
            else
            {
                throw new ArgumentException("Your move command is out of area.");
            }
            return(roverPosition);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Simulate all moves according to user position step by step
        /// </summary>
        /// <param name="userAndMoves"> user last position and next moves</param>
        /// <returns></returns>


        /// <summary>
        /// Fill user and moves
        /// </summary>
        /// <returns></returns>
        private Tuple <RoverPosition, string> getRoverAndMoves()
        {
            RoverPosition user      = getRoverDetailFromInput();
            string        userMoves = getSafeStringFromUser()[0];

            return(new Tuple <RoverPosition, string>(user, userMoves));
        }
Exemplo n.º 10
0
 private static void isValidPosition(RoverPosition roverPosition, int maxXCoordinate, int maxYCoordinate)
 {
     if (roverPosition.CurrentXIndex > maxXCoordinate || roverPosition.CurrentXIndex < 0 || roverPosition.CurrentYIndex > maxYCoordinate || roverPosition.CurrentYIndex < 0)
     {
         throw new Exception(string.Concat("OutOfSurface for user: ", roverPosition.ToString()));
     }
 }
Exemplo n.º 11
0
        public RoverPosition Navigate(RoverPosition start, string command)
        {
            char[] actions = command.ToCharArray();

            for (var i = 0; i < actions.Length; i++)
            {
                switch (actions[i])
                {
                case 'L':
                    start = TurnLeft(start);
                    break;

                case 'R':
                    start = TurnRight(start);
                    break;

                case 'M':
                    start = Move(start);
                    break;

                default:
                    break;
                }
            }


            return(start);
        }
Exemplo n.º 12
0
        private RoverPosition Move(RoverPosition start)
        {
            var backup = new RoverPosition()
            {
                Name = start.Name, Direction = start.Direction, X = start.X, Y = start.Y
            };

            switch (start.Direction)
            {
            case 'E':
                start.X++;
                break;

            case 'S':
                start.Y--;
                break;

            case 'W':
                start.X--;
                break;

            case 'N':
                start.Y++;
                break;

            default:
                break;
            }

            // Validate the movement
            return(_environmentSerive.ValidateMove(start)?start : backup);
        }
Exemplo n.º 13
0
        private RoverPosition ParsePosition(string roverPositionInput)
        {
            var roverPositionArray = roverPositionInput.Split(' ');

            if (roverPositionArray.Length == 3)
            {
                string orientation = roverPositionArray[2].ToUpper();

                if (orientation.Equals("N", StringComparison.InvariantCultureIgnoreCase) ||
                    orientation.Equals("S", StringComparison.InvariantCultureIgnoreCase) ||
                    orientation.Equals("E", StringComparison.InvariantCultureIgnoreCase) ||
                    orientation.Equals("W", StringComparison.InvariantCultureIgnoreCase))
                {
                    RoverPosition roverPosition = new RoverPosition()
                    {
                        Orientation = (Orientation)Enum.Parse(typeof(Orientation), orientation),
                        X           = int.Parse(roverPositionArray[0]),
                        Y           = int.Parse(roverPositionArray[1])
                    };

                    return(roverPosition);
                }
            }

            return(null);
        }
Exemplo n.º 14
0
        public void TestRoverPositionEquality()
        {
            var position1 = new RoverPosition(new Point(1, 1), MarsRover.CardinalDirection.East);
            var position2 = new RoverPosition(new Point(1, 1), MarsRover.CardinalDirection.East);

            Assert.IsTrue(position1.GetHashCode().Equals(position2.GetHashCode()));
            Assert.IsTrue(position1.Equals(position2));
        }
Exemplo n.º 15
0
        public void SetUp_Rover()
        {
            var roverPosition = new RoverPosition {
                Coordinate = new Point(5, 2), Heading = Heading.S
            };

            _rover = new Rover(roverPosition);
        }
Exemplo n.º 16
0
        public IExecutionResult DeployRover(string roverPositionInput, Identity plateauSurfaceId)
        {
            RoverPosition roverPosition = ParsePosition(roverPositionInput);

            Emit(new DeployRoverEvent(roverPosition, plateauSurfaceId));

            return(ExecutionResult.Success());
        }
Exemplo n.º 17
0
 public RoverPosition GetUpdatedPositionOnExecutingCommand(char instruction, RoverPosition position)
 {
     if (Instruction.Move == (Instruction)instruction)
     {
         return(_action.MoveForward(position));
     }
     return(_action.Rotate(position, (Instruction)instruction));
 }
Exemplo n.º 18
0
 public RoverPosition Rotate(RoverPosition position, Instruction instruction)
 {
     if (Instruction.Left == instruction)
     {
         return(GetPositionOnLeftRotate(position));
     }
     return(GetPositionOnRightRotate(position));
 }
Exemplo n.º 19
0
        private static void ManageRovers()
        {
            IRoverEngineService     roverEngineService = new RoverEngineService();
            List <ValidationErrors> validationErrors   = new List <ValidationErrors>();

            string roverCurrentPosition                  = string.Empty;
            string roverNavigationInstruction            = string.Empty;
            List <RoverPosition> completedRoverPositions = new List <RoverPosition>();
            RoverPosition        currentRoverPosition    = new RoverPosition();

            Console.WriteLine("Please enter the boundaries of the grid followed by a line for the current position of the rover \n and a line for the exploration path the rover needs to follow. Once all the information has been entered please enter \\ to send instructions to the rovers.");

            string input = string.Empty;

            do
            {
                input = Console.ReadLine();
                userInput.Add(input);
            } while (input != "\\");

            if (!roverEngineService.ValidateUserInput(userInput, out validationErrors))
            {
                Console.WriteLine("The following errors occured in given input");
                foreach (var validationError in validationErrors)
                {
                    Console.WriteLine(string.Format("Line No.{0}:{1}", validationError.LineNo, validationError.ValidationMessage));
                }
                Console.ReadLine();
                return;
            }

            roverEngineService.SetGridBoundaries(marsGrid, userInput[0]);
            for (int index = 1; index < userInput.Count; index++)
            {
                if (index % 2 == 0)
                {
                    try
                    {
                        completedRoverPositions.Add(roverEngineService.NavigateRover(marsGrid, currentRoverPosition, userInput[index]));
                    }
                    catch (PlanetOutOfBoundsException ex)
                    {
                        Console.WriteLine("Error on Rover No. {0}.{1}", (index / 2), ex.Message);
                    }
                }
                else
                {
                    currentRoverPosition = roverEngineService.GetRoverPosition(userInput[index]);
                }
            }

            foreach (var item in completedRoverPositions)
            {
                Console.WriteLine("{0} {1} {2}", item.XPosition, item.YPosition, item.Direction);
            }

            Console.ReadLine();
        }
Exemplo n.º 20
0
        public RoverPosition RoverLocation(string command, List <Coordinate> areaOfRover)
        {
            var roverLocation = new RoverPosition();
            var location      = command.Split(' ');

            if (location.Length == 3)
            {
                var direction = DirectionType.None;
                if (!int.TryParse(location[0], out var xCoordinate))
                {
                    throw new ArgumentException("Invalid character for X value.");
                }
                if (!int.TryParse(location[1], out var yCoordinate))
                {
                    throw new ArgumentException("Invalid character for Y value.");
                }

                switch (location[2])
                {
                case "N":
                    direction = DirectionType.North;
                    break;

                case "S":
                    direction = DirectionType.South;
                    break;

                case "E":
                    direction = DirectionType.East;
                    break;

                case "W":
                    direction = DirectionType.West;
                    break;
                }

                if (direction.Equals(DirectionType.None))
                {
                    throw new ArgumentException("Invalid character for direction value");
                }

                var coordinate = new Coordinate {
                    X = xCoordinate, Y = yCoordinate
                };
                var isCoordinateOnArea = areaOfRover.FirstOrDefault(x => x.X == xCoordinate && x.Y == yCoordinate);

                if (isCoordinateOnArea == null)
                {
                    throw new ArgumentException("Rover's first location is out of area.");
                }

                roverLocation = new RoverPosition {
                    Direction = direction, Coordinate = coordinate
                };
            }

            return(roverLocation);
        }
Exemplo n.º 21
0
        public RoverBase(RoverPosition firstRoverPosition, RoverPosition secondRoverPosition, Plateau plateau)
        {
            this.firstRoverPosition  = firstRoverPosition;
            this.secondRoverPosition = secondRoverPosition;
            this.plateau             = plateau;

            ConfirmConstructor();
            this.plateau.ConfirmPlateauIsValid();
        }
Exemplo n.º 22
0
        public void RoverPosition_Should_Be_Changed_By_Control_Signal(RoverPosition position,
                                                                      RoverControlSignal controlSignal, RoverPosition expectedPosition)
        {
            var newPosition = position.CalculateNewPosition(controlSignal);

            newPosition.X.ShouldBe(expectedPosition.X);
            newPosition.Y.ShouldBe(expectedPosition.Y);
            newPosition.Heading.ShouldBe(expectedPosition.Heading);
        }
Exemplo n.º 23
0
        public void LastRoverPosition_Should_Be_Calculated(RoverPosition position, RoverControlSignal[] controlSignals,
                                                           RoverPosition expectedPosition)
        {
            var newPosition = position.CalculateLastPosition(controlSignals);

            newPosition.X.ShouldBe(expectedPosition.X);
            newPosition.Y.ShouldBe(expectedPosition.Y);
            newPosition.Heading.ShouldBe(expectedPosition.Heading);
        }
Exemplo n.º 24
0
        public string GetRoversCurrentPosition([FromBody] RoverPosition roverPosition)
        {
            if (ModelState.IsValid)
            {
                return(_roverMovementService.RoverMovement(roverPosition));
            }

            return("Please provide valid inputs");
        }
 public void ShouldParseValidInput()
 {
     var parser = new RoverPositionParser();
     var result = parser.Parse("1 2 W");
     var expected = new RoverPosition(new Coordinate(1, 2), Compass.West);
     result.Direction.ShouldEqual(expected.Direction);
     result.Coordinate.X.ShouldEqual(result.Coordinate.X);
     result.Coordinate.Y.ShouldEqual(result.Coordinate.Y);
 }
Exemplo n.º 26
0
        public void RoverPosition_Should_Be_Created_From_Position_Format(string positionFormat, int x, int y,
                                                                         CardinalCompassPoint heading)
        {
            var roverPosition = RoverPosition.CreateFromPositionFormat(positionFormat);

            roverPosition.X.ShouldBe(x);
            roverPosition.Y.ShouldBe(y);
            roverPosition.Heading.ShouldBe(heading);
        }
        public void FinalPosition_Position3_MovementSignals3_ReturnSuccess()
        {
            var roverCurrentPosition = new RoverPosition()
            {
                Plateau = "5 5", Position = "2 3 W", MovementSignals = "MMLMMLMM"
            };
            IRoverMovementService roverMovement = new RoverMovementService();

            Assert.Equal("2 1 E", roverMovement.RoverMovement(roverCurrentPosition));
        }
        public void FinalPosition_Position2_MovementSignals2_ReturnSuccess()
        {
            var roverCurrentPosition = new RoverPosition()
            {
                Plateau = "5 5", Position = "3 3 E", MovementSignals = "MMRMMRMRRM"
            };
            IRoverMovementService roverMovement = new RoverMovementService();

            Assert.Equal("5 1 E", roverMovement.RoverMovement(roverCurrentPosition));
        }
        public void FinalPosition_Position1_MovementSignals1_ReturnSuccess()
        {
            var roverCurrentPosition = new RoverPosition()
            {
                Plateau = "5 5", Position = "1 2 N", MovementSignals = "LMLMLMLMM"
            };
            IRoverMovementService roverMovement = new RoverMovementService();

            Assert.Equal("1 3 N", roverMovement.RoverMovement(roverCurrentPosition));
        }
        public void TestSenario_DirectionS_TurnLeft()
        {
            var expectedOutput = Direction.E;
            var userPosition   = new RoverPosition(0, 0, Direction.S);

            userPosition.TurnLeft();
            var actualOutput = userPosition.Direction;

            Assert.AreEqual(expectedOutput, actualOutput);
        }
Exemplo n.º 31
0
 public void Put([FromBody] RoverPosition max)
 {
     try
     {
         _environmentService.MaxX = max.X;
         _environmentService.MaxY = max.Y;
     }
     catch
     { }
 }