Flipkart Interview Question
SDE-2sCountry: United States
Nothing fancy, short and simple... I'm keeping track of the direction that the robot is facing. I mod on the direction which then dictates how to update our (x,y) coordinates.
def robot_moves(moves):
direction = 0
move_sets = [[0,0]]
for move in moves:
if move == "L":
direction += 1
elif move == "R":
direction -= 1
elif move == "G":
set_ = move_sets[-1].copy()
print(set_)
if direction % 4 == 0:
set_[0] += 1
elif direction % 4 == 1:
set_[1] -= 1
elif direction % 4 == 2:
set_[0] -= 1
elif direction % 4 == 3:
set_[1] += 1
if set_ in move_sets:
return True
move_sets.append(set_)
return False
Imagine you are in the Point Origin with (0,0). Clearly, movement can be only X,Y. Thus, the way to handle it is simply keeping track of the co-ordinates in a set, and check if I have visited the point before or not.
- NoOne April 27, 2019If I did, I am inside a loop.
One more thing. The question is incomplete. It also should give the direction the robot is facing right now, is it N,E,W, S ?