Java Data Structure: robot walking, java Data Structure Robot
A group of robot cars were introduced in a Children's Palace. It can accept pre-input instructions and act according to instructions. The basic action of a car is very simple. There are only three types: Left turn (marked as L), right turn (marked as R), forward several centimeters (directly remember the number ).
For example, you can enter the following command for the car:
15L10R5LRR10R20
Then, the car first goes straight 15 cm, turn left, then go 10 cm, then turn right ,...
It is not hard to see that for this command string, the car is back to the departure location.
Your task is to write a program. The user enters the command, and the program outputs the straight distance between the vehicle location and the car location before the command execution.
[Input and output format requirements]
The user first enters an integer n (n <100), indicating that there will be n commands.
Next, enter n commands. Each instruction is composed of only L, R, and numbers (the number is 0 ~ Integer between 100)
The length of each instruction cannot exceed 256 characters.
The program outputs n rows of results.
Each result indicates the linear distance between the front and back of the vehicle to execute the corresponding command. It must be rounded to the last two digits of the decimal number.
For example, user input:
5
L100R50R10
3LLL5RR4L12
LL
100R
5L5L5L5
Program output:
102.96
9.06
0.00
100.00
0.00
Code:
import java.util.*; class FuShu { public double real; public double image; public FuShu() { real = 0; image = 0; } public FuShu(double r, double i) { real = r; image = i; } public FuShu dot(FuShu x) { FuShu r = new FuShu(); r.real = real * x.real - image * x.image; r.image = real * x.image + image * x.real; return r; } public FuShu dot(double r, double i) { FuShu t = new FuShu(); t.real = real * r - image * i; t.image = real * i + image * r; return t; } } class Robot { private int x = 0; private int y = 0; private FuShu dir = new FuShu(1,0); public void walk(String s) { int sum = 0; for(int i=0; i<s.length(); i++) { char c = s.charAt(i); if(c=='L' || c=='R') { x += sum * dir.real; y += sum * dir.image; sum = 0; if(c=='L') dir = dir.dot(0,1); else dir = dir.dot(0,-1); } else sum = sum * 10 + (c-'0'); } x += sum * dir.real; y += sum * dir.image; } public void show() { double d = Math.sqrt(x*x + y*y); System.out.println(x+","+y + " dir: " + dir.real + "," + dir.image + ", d=" + d); } } public class Walk { public static void main(String[] args) throws Exception { Robot t = new Robot(); t.walk("3R4"); t.show(); } }
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.