机器人给定动作之后的 C++ 位置
在该问题中,给定一个机器人,它只能向四个方向之一移动一步。方向有向上(“U”)、向下(“D”)、向左(“L”)、向右(“R”)。并且给定一个字符串,其中包含数字方向的首字母。我们的任务是打印出机器人的最终位置,已给定机器人初始位置为 (0,0)。
让我们举个例子来理解这个问题
输入 − 输入:'LDRRUL'
输出 − (0, 0)
说明 −
L (left) : (0,0) -> (-1,0) D (down) : (-1,0) -> (-1, -1) R (right) : (-1, -1) -> (0, -1) R (right) : (0, -1) -> (1, -1) U(up) : (1, -1) -> (1, 0) L(left) : (1, 0) -> (0, 0)
为了解决这个问题,我们将计算 x 轴和 y 轴方向上的总步数。对于 x 坐标,增加向右移动的计数,减少向左移动的计数。对于 y 坐标,增加向上移动的计数,减少向左移动的计数。
示例
显示我们解决办法实现的程序
#include <iostream>
#include <string.h>
using namespace std;
void robotMoved(string move) {
int xAxis, yAxis;
int l=move.size();
for (int i = 0; i < l; i++) {
if (move[i]=='U')
yAxis++;
else if (move[i]=='D')
yAxis--;
else if (move[i]=='L')
xAxis--;
else if (move[i]=='R')
xAxis++;
}
cout<<"Final Position of the robot is : ("<<xAxis<<", "<<yAxis<<")"<<endl;
}
int main() {
string move="URLLDDRRUDUDDRU";
robotMoved(move);
return 0;
}输出
Final Position of the robot is : (32744, -274873553)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP