机器人可以在四个方向上在飞机上移动:U-上,D-下,L-左,R-右。交通示例是UUDLR,DLRUD。我必须实现“步行”方法,以便它在经过指示的路径后返回机器人位置。所以我这样做:
class Main {
static int[] walk(String path) {
int[] A = {0,0};
char charFromPath;
for (int i = 0 ; i < path.length() ; i++) {
charFromPath = path.charAt(i);
if(charFromPath == 'U')
{
A[1]++;
}
if(charFromPath == 'D')
{
A[1]--;
}
if(charFromPath == 'L')
{
A[0]--;
}
if(charFromPath == 'R')
{
A[0]++;
}
}
return A;
}
public static void main(String[] args) {
{
String path="UUDLR";
int[] position = walk(path);
System.out.println("case 1 - path "+path+ " position 0,1");
if(position[0]==0 && position[1]==1)
System.out.println("the robot went right");
else
System.out.println("the robot smashed");
}
{
String path="DLRUD";
int[] position = walk(path);
System.out.println("\ncase 2 - path "+path+ " position 0,-1");
if(position[0]==0 && position[1]==-1)
System.out.println("the robot went right");
else
System.out.println("the robot smashed");
}
}}
现在在版本2 中,根据逻辑U,D,L,R,命令为UP DOWN LEFT RIGHT。交通示例为UPUPLEFTRIGHTUP。
版本3 中的命令现在是3xUP 2xLEFT DOWN RIGHT。 3xUP表示向上移动三倍,向左移动2xLEFT 2次。为机器人增加运动限制,他不能超出10x10区域(项目10.10或-10,-10是最后一个有效值)。
我不知道该怎么写。如何计算字符串中重复字符串的数量?
答案 0 :(得分:1)
对于版本2,您可以拆分原始字符串,然后使用可以调用字符串String [] tmpsplit = tmp.split(" ");
的方法将其放入数组。这样,您的数组在每个单元格内都有一个方向(向上或向下或向左或向右)。
然后,您可以将该数组与版本1中的数组类似。将charFromPath == 'U'
替换为tmpsplit[i].equals("UP")
答案 1 :(得分:1)
您可以尝试类似
String str = "UPUPLEFTRIGHTUP";
int countUP = ( str.split("UP", -1).length ) - 1;
int countLEFT = ( str.split("LEFT", -1).length ) - 1;
int countRIGHT = ( str.split("RIGHT", -1).length ) - 1;
int countDOWN = ( str.split("DOWN", -1).length ) - 1;
可以通过将int
的值与框的限制(在您的情况下为10*10
)进行比较来验证限制。
对于位置,如果我们假设每个运动为1个单位,则:
int x = 0; //starting point in Ox axis
int y = 0; //starting point in Oy axis
x = countRIGHT - CountLeft;
y = countUP - CountDOWN;
这对(x,y)
是机器人的位置。
int[] walk(String path) {
int[] position = {0,0};
int countUP = ( path.split("UP", -1).length ) - 1; //Counts how many UP command
int countLEFT = ( path.split("LEFT", -1).length ) - 1; //Counts how many LEFT command
int countRIGHT = ( path.split("RIGHT", -1).length ) - 1; //Counts how many RIGHT command
int countDOWN = ( path.split("DOWN", -1).length ) - 1; //Counts how many DOWN command
position[0] = countRIGHT - countLEFT;
position[1] = countUP - countDown;
return position;
}