In: Computer Science
The input will be a String with multiple not-always-lowercase directions separated by underscores. The last character of the input is always an underscore. You must output the final (x, y) coordinates of a robot, starting at (0, 0), after it has followed all of the directions. Print the result in the format “Result: (x, y)”
USE THE SKELETON PROGRAM PROVIDED.
Example #1:
INPUT: up_down_left_down_down_
Result: (-1, -2)
up --move→ y + 1 = 1
down --move→ y - 1 = 0
left --move→ x - 1 = -1
down --move→ y - 1 = -1
down --move→ y - 1 = -2
x = -1, y = -2 at the end
Example #2:
INPUT: up_dOwn_riGHt_LefT_
Result: (0, 0)
/*
* Notice the globally-scoped x and y variables at the top of the class */
import java.util.Scanner;
public class Robot {
public static int x = 0;
public static int y = 0;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String directions = console.nextLine();
readDirections(directions);
}
// Isolates each direction as a String in a loop
public static void readDirections(String dirs) {
}
// Moves the robot by editing the x and y variables
public static void move(String dir) {
}
}
Program: In this program, given an input string of directions, we calculate the final (x, y) coordinates of a robot, starting at (0, 0), after it has followed all of the directions. Inside the function readDirections(String dirs) we process the string- convert it to lowercase, remove the ending underscore, then split it into an array based on the regex underscore and then to update the coordinates, traverse each direction in a loop and call move(String dirs) function. Indside the move() function, we update x,y based on direction value.
Code:
import java.util.Scanner; public class Robot { public static int x = 0; public static int y = 0; public static void main(String[] args) { Scanner console = new Scanner(System.in); String directions = console.nextLine(); readDirections(directions); System.out.println("(" + x + ", " + y + ")"); } // Isolates each direction as a String in a loop public static void readDirections(String dirs) { // Convert string to lowercase dirs = dirs.toLowerCase(); // Remove ending underscore dirs = dirs.substring(0, dirs.length() - 1); // Split array based on underscore // Example: dirs = "up_down_left_down_down" -> dirArray = {"up","down","left","down","down"} String[] dirArray = dirs.split("_"); // Traverse each directions and call move() function for (int i = 0; i < dirArray.length; i++) { move(dirArray[i]); } } // Moves the robot by editing the x and y variables public static void move(String dir) { // Check if direction is up, down, left or right if (dir.equals("up")) { y++; } else if (dir.equals("down")) { y--; } else if (dir.equals("left")) { x--; } else { x++; } } }
Output 1:
Output 2: