机器人行走

package org.bluebridge.topics;

/*机器人行走
 某少年宫引进了一批机器人小车。可以接受预先输入的指令,按指令行动。
 小车的基本动作很简单,只有3种:左转(记为L),右转(记为R),向前走若干厘米(直接记数字)。

 例如,我们可以对小车输入如下的指令:
 15L10R5LRR10R20
 则,小车先直行15厘米,左转,再走10厘米,再右转,...
 不难看出,对于此指令串,小车又回到了出发地。
 你的任务是:编写程序,由用户输入指令,程序输出每条指令执行后小车位置与指令执行前小车位置的直线距离。

 【输入、输出格式要求】
 用户先输入一个整数n(n<100),表示接下来将有n条指令。
 接下来输入n条指令。每条指令只由L、R和数字组成(数字是0~100之间的整数)
 每条指令的长度不超过256个字符。
 程序则输出n行结果。
 每条结果表示小车执行相应的指令前后位置的直线距离。要求四舍五入到小数后2位。

 例如:用户输入:
 5
 L100R50R10
 3LLL5RR4L12
 LL
 100R
 5L5L5L5

 则程序输出:
 102.96
 9.06
 0.00
 100.00
 0.00
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RobotWalking {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(br.readLine());
		String[] result = new String[n];// 保存结果的数组
		int counts = 0;
		while (n > 0) {
			String data = br.readLine();// 输入指令
			int[] dir = new int[] { 1, -1, -1, 1 };// 方向数组
			// x:距离出发点的水平距离;y:距离出发点竖直距离,count:记录多少次转弯(偶数次,竖直距离发生变化;奇数次,水平距离发生变化)
			int x = 0, y = 0, count = 0;
			int start = 0;
			for (int i = 0; i < data.length() - 1; i++) {
				char c = data.charAt(i);
				if (c == 'L' || c == 'R') {
					String str = data.substring(start, i);
					int distance = str.equals("") ? 0 : Integer.parseInt(str);
					start = i + 1;
					if (count % 2 == 0) {
						y += distance * dir[count];
					} else {
						x += distance * dir[count];
					}
					if (c == 'L')
						count = count + 1 == 4 ? 0 : count + 1;
					else
						count = count - 1 == -1 ? 3 : count - 1;
				}
			}
			//别忘了最后一个字符
			char c = data.charAt(data.length() - 1);
			int distance = 0;
			if (c != 'L' && c != 'R') {
				String str = data.substring(start, data.length());
				distance = str.equals("") ? 0 : Integer.parseInt(str);
			} else {
				String str = data.substring(start, data.length() - 1);
				distance = str.equals("") ? 0 : Integer.parseInt(str);
			}

			if (count % 2 == 0)
				y += distance * dir[count];
			else
				x += distance * dir[count];
			String xy = String.format("%.2f", Math.sqrt(x * x + y * y));
			result[counts++] = xy;
			n--;
		}
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值