The java data structure enables the robot to walk

  • 2021-01-14 05:56:04
  • OfStack

A children's palace has introduced a batch of robot cars. Can accept the pre-input instruction, according to the instruction action. The basic action of the car is very simple, there are only 3 kinds: turn left (marked L), turn right (marked R), and go forward a few centimeters (marked directly by numbers).

For example, we can input the following command to the car:

15L10R5LRR10R20

Then, the car first straight 15 centimeters, left, then walk 10 centimeters, and then turn right...

It is not difficult to see that for this command string, the car is back to the starting point.

Your task is: write a program, the user input instructions, the program output each instruction after the execution of the car position and the car before the execution of the straight-line distance.

[Input and output format requirements]

The user enters an integer n (n) < 100), indicating that an n instruction will follow.

Next, enter the n instruction. Each instruction consists only of L, R and numbers (numbers are integers between 0 and 100)

Each instruction is no longer than 256 characters.

The program outputs the n line results.

Each result represents the straight-line distance before and after the car executes the corresponding instruction. We want 4 to round 5 to the last two decimal places.

For example, user input:

5
L100R50R10
3LLL5RR4L12
LL
100R
5L5L5L5

Then the 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(); 
 } 
}

Related articles: