Robot moves 1 right or 2 up

Calculate the number of ways a robot can get from a position 0,0 to a position X,Y (without getting out of the board with corners 0,0 and X,Y) if the robot can only move either 1 position to right, or 2 up.

Assuming that the robot always starts at 0,0, and the board is size X,Y, which is also where the robot needs to get, a solution in Python would be:


def robot(x,y):
    if x == 0 and y == 0:
        return 1;
    if x < 0 or y < 0:
        return 0;
    return robot(x-1, y) + robot(x, y-2)

If we want to specify any starting position in the board, and different limits in board from final position, this could be a solution:

def robot(x, y, xend, yend, xlimit, ylimit):
    if x > xlimit or y > ylimit or x < 0 or y < 0:
        return 0
    if x == xend and y == yend:
        return 1
    return robot(x+1, y, xend, yend, xlimit, ylimit) + robot(x, y+1, xend, yend, xlimit, ylimit)

Leave a comment