A certain Youth Palace introduced a batch of robot cars. You can accept pre-entered instructions and follow them. The basic movements of a car are very simple, there are only 3 types: turn left (recorded as L), turn right (recorded as R), and walk forward a few centimeters (record directly).
For example, we can enter the following command to the car:
15L10R5LRR10R20
Then, the car will first go straight for 15 cm, turn left, then walk 10 cm, then turn right,...
It is not difficult to see that for this command string, the car returned to its starting point.
Your task is: write a program, input instructions by the user, and the program outputs the straight line distance between the car position after each instruction is executed and the car position before the instruction is executed.
[Input and output format requirements]
The user first enters an integer n (n<100), indicating that there will be n instructions next.
Next enter n instructions. Each instruction consists of only L, R and numbers (numbers are integers between 0 and 100)
Each instruction has no more than 256 characters in length.
The program outputs n lines of results.
Each result represents the straight line distance between the front and rear positions of the carriage when executing the corresponding command. Requires rounding to 2 decimal places.
For example: User input:
5
L100R50R10
3LLL5RR4L12
LL
100R
5L5L5L5
Then the program outputs:
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 to everyone's learning and I hope everyone will support Wulin.com more.