From 6b9bbc026de8a5058d10c533b01e7fb3cbcb90c6 Mon Sep 17 00:00:00 2001 From: 8ACE8 Date: Tue, 25 Feb 2025 23:53:02 +0300 Subject: [PATCH] Fix robot movement logic: prevent extra steps and optimize turns --- src/main/java/core/basesyntax/RobotRoute.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/core/basesyntax/RobotRoute.java b/src/main/java/core/basesyntax/RobotRoute.java index 351ca4b9..6f4f7307 100644 --- a/src/main/java/core/basesyntax/RobotRoute.java +++ b/src/main/java/core/basesyntax/RobotRoute.java @@ -2,6 +2,36 @@ public class RobotRoute { public void moveRobot(Robot robot, int toX, int toY) { - //write your solution here + if (robot.getX() < toX) { + while (robot.getDirection() != Direction.RIGHT) { + robot.turnRight(); + } + while (robot.getX() < toX) { + robot.stepForward(); + } + } else if (robot.getX() > toX) { + while (robot.getDirection() != Direction.LEFT) { + robot.turnLeft(); + } + while (robot.getX() > toX) { + robot.stepForward(); + } + } + + if (robot.getY() < toY) { + while (robot.getDirection() != Direction.UP) { + robot.turnRight(); + } + while (robot.getY() < toY) { + robot.stepForward(); + } + } else if (robot.getY() > toY) { + while (robot.getDirection() != Direction.DOWN) { + robot.turnLeft(); + } + while (robot.getY() > toY) { + robot.stepForward(); + } + } } }