题目描述
开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
输入:
合法坐标为A(或者D或者W或者S) + 数字(两位以内)
坐标之间以;分隔。
非法坐标点需要进行丢弃。如AA10; A1A; $%$; YAD; 等。
下面是一个简单的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
处理过程:
起点(0,0)
+ A10 = (-10,0)
+ S20 = (-10,-20)
+ W10 = (-10,-10)
+ D30 = (20,-10)
+ x = 无效
+ A1A = 无效
+ B10A11 = 无效
+ 一个空 不影响
+ A10 = (10,-10)
结果 (10, -10)
注意请处理多组输入输出
输入描述:
一行字符串
输出描述:
最终坐标,以,分隔
示例1
输入
A10;S20;W10;D30;X;A1A;B10A11;;A10;
输出
10,-10
JAVA实现
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine())
{
int x=0;
int y=0;
String[] temp=scanner.nextLine().split(";");
for(int i=0;i<temp.length;i++)
{
try {
int a=Integer.parseInt(temp[i].substring(1, temp[i].length()));
char dir=temp[i].charAt(0);
if(dir=='A')
{
x-=a;
}
if(dir=='D')
{
x+=a;
}
if(dir=='W')
{
y+=a;
}
if(dir=='S')
{
y-=a;
}
}
catch(Exception e){
continue;
}
}
System.out.println(x+","+y);
}
}
}
Python实现
1.
import sys
for line in sys.stdin:
x,y=0,0
for temp in line.split(';'):
try:
a = int(temp[1:])
if temp[0] == "A":
x -= a
if temp[0] == "D":
x += a
if temp[0] == "W":
y += a
if temp[0] == "S":
y -= a
except:
pass
print("%d,%d"%(x,y))
2.
import sys
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
for line in sys.stdin:
x,y=0,0
for cmd in line.split(';'):
cmd = cmd.strip()
if cmd and cmd[0] in 'ASWD':
try:
n=int(cmd[1:])
x+=n*dx['ASWD'.find(cmd[0])]
y+=n*dy['ASWD'.find(cmd[0])]
#print cmd, n, x, y
except:
pass
print "%d,%d"%(x,y)
C++实现
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string input;
while (cin >> input)
{
int x = 0, y = 0;
vector<string> ve;
int len = 0;
for (int i = 0; i < input.length(); ++i)
{
if (input[i] != ';')
{
len++;
continue;
}
ve.push_back(input.substr(i - len, len));
len = 0;
}
for (int i = 0; i < ve.size(); i++)
{
int num = 0;
if (ve[i].length() == 3 && ve[i][1] >= '0'&&ve[i][1] <= '9'&&ve[i][2] >= '0'&&ve[i][2] <= '9')
num = (ve[i][1] - '0') * 10 + (ve[i][2] - '0');
if (ve[i].length() == 2 && ve[i][1] <= '9'&&ve[i][1] >= '0')
num = (ve[i][1] - '0');
if (ve[i].length() == 1)
num = 0;
switch (ve[i][0])
{
case 'A': x -= num; break;
case 'D': x += num; break;
case 'S': y -= num; break;
case 'W': y += num; break;
default:break;
}
}
cout << x << "," << y << endl;
}
return 0;
}