Data Structures & AlgorithmsHardTCS NQT Digital · simulation

Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns 90 degrees left and R turns 90 degrees right. Run the code on the command string 'FFRFFLBRF'. What is the final position?

Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns 90 degrees left and R turns 90 degrees right. Run the code on the command string 'FFRFFLBRF'. What is the final position?
def robot(cmds):
    x = y = 0
    dx, dy = 0, 1
    for c in cmds:
        if c == 'L':
            dx, dy = -dy, dx
        elif c == 'R':
            dx, dy = dy, -dx
        elif c == 'F':
            x += dx
            y += dy
        elif c == 'B':
            x -= dx
            y -= dy
    return (x, y)
print(robot('FFRFFLBRF'))
What is printed?
  1. A. (3, 1)
  2. B. (3, 0)
  3. C. (2, 1)
  4. D. (1, 3)

Correct answer: A. (3, 1)

After FFRFF the robot is at (2, 2) facing east; then L, B, R, F leave it at (3, 1). Mixing up the turn direction flips the sign of the final x coordinate.

More Coding Interview Problems questions

Exams that ask this topic