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?- A. (3, 1)
- B. (3, 0)
- C. (2, 1)
- 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
- Problem: What is the KMP prefix-function array pi for the string 'ababaca'? python s = 'ababaca' pi = [0] len(s) for i in range(1…
- Problem: What is the lexicographically smallest rotation of 'bcabca'? python s = 'bcabca' print(min(s[i:] + s[:i] for i in range(len(s))))…
- Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the…
- Problem: How many ways can a staircase of 8 steps be climbed if each move climbs 1, 3 or 4 steps? Run the DP below. python ways = [0] 9…
- Problem: Jobs are given as (deadline, profit): (2,100), (1,19), (2,27), (1,25), (3,15). Each job takes one unit slot and must finish by…
- Problem: Compute C(10, 3) mod 7 using Lucas' theorem, where 7 is prime. What is the result?