VOOZH about

URL: https://www.geeksforgeeks.org/dsa/position-of-robot-after-given-movements/

⇱ Position of robot after given movements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Position of robot after given movements

Last Updated : 27 Jul, 2022

Given a robot which can only move in four directions, UP(U), DOWN(D), LEFT(L), RIGHT(R). Given a string consisting of instructions to move. Output the coordinates of a robot after executing the instructions. Initial position of robot is at origin(0, 0).

Examples: 

Input : move = "UDDLRL" 
Output : (-1, -1)

Explanation:
 Move U : (0, 0)--(0, 1)
 Move D : (0, 1)--(0, 0)
 Move D : (0, 0)--(0, -1)
 Move L : (0, -1)--(-1, -1)
 Move R : (-1, -1)--(0, -1)
 Move L : (0, -1)--(-1, -1)
 Therefore final position after the complete
 movement is: (-1, -1)

Input : move = "UDDLLRUUUDUURUDDUULLDRRRR"
Output : (2, 3)

Source: Goldman Sachs Interview Experience | Set 36 .

Approach: Count number of up movements (U), down movements (D), left movements (L) and right movements (R) as countUp, countDown, countLeft and countRight respectively. Final x-coordinate will be 
(countRight - countLeft) and y-coordinate will be (countUp - countDown).

Below is the implementation of the above idea:


Output
Final Position: (2, 3)
Comment
Article Tags: