機器人給定動作之後的 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)

更新於: 2020 年 4 月 17 日

1000+ 瀏覽

開啟您的 職業生涯

完成課程獲取認證

啟動
廣告