From 5541fbb98d8eff4bba74e0807dc5ff74bfb9a0b3 Mon Sep 17 00:00:00 2001 From: Artur Date: Tue, 2 Apr 2024 22:56:47 +0200 Subject: [PATCH] jv-robot-task-completed --- src/main/java/core/basesyntax/RobotRoute.java | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/src/main/java/core/basesyntax/RobotRoute.java b/src/main/java/core/basesyntax/RobotRoute.java index 351ca4b9..743afb86 100644 --- a/src/main/java/core/basesyntax/RobotRoute.java +++ b/src/main/java/core/basesyntax/RobotRoute.java @@ -1,7 +1,46 @@ package core.basesyntax; public class RobotRoute { - public void moveRobot(Robot robot, int toX, int toY) { - //write your solution here + public static void moveRobot(Robot robot, int toX, int toY) { + int currentX = robot.getX(); + int currentY = robot.getY(); + + int diffX = toX - currentX; + int diffY = toY - currentY; + + while (diffX != 0 || diffY != 0) { + if (diffX > 0) { + turnAndMove(robot, Direction.RIGHT); + diffX--; + } else if (diffX < 0) { + turnAndMove(robot, Direction.LEFT); + diffX++; + } + + if (diffY > 0) { + turnAndMove(robot, Direction.UP); + diffY--; + } else if (diffY < 0) { + turnAndMove(robot, Direction.DOWN); + diffY++; + } + } + } + + private static void turnAndMove(Robot robot, Direction direction) { + while (robot.getDirection() != direction) { + robot.turnRight(); + } + robot.stepForward(); + } + + public static void main(String[] args) { + Robot robot = new Robot(Direction.RIGHT, 0, 0); + int toX = 3; + int toY = 4; + + System.out.println("Initial position: X = " + robot.getX() + ", Y = " + robot.getY()); + moveRobot(robot, toX, toY); + System.out.println("Final position: X = " + robot.getX() + ", Y = " + robot.getY()); } }