Skip to the content

The rover heading home

Problem

Every command takes twenty minutes to reach Mars, so the rover gets them all at once, as arrows, and moves one square per arrow. When it stops, mission control wants to know how many steps it is from the base.

Write a function that takes a string made only of ^ (one square up), v (down), < (left) and > (right), and returns a whole number: the horizontal steps plus the vertical steps between the rover and where it started, no matter which side it ended up on.

With ">>^^^<v" it moves 2 right and 1 left, so it is 1 off sideways; it goes up 3 and down 1, so it is 2 off vertically: you return 3.

Opposite arrows cancel out: "^v" gives 0. Arrows on different axes do not: "^<" gives 2. An empty string gives 0.

Examples

  • The example

    ">>^^^<v" → 3

  • Back where it started

    "^v<>" → 0

  • Up and left do not cancel

    "^<" → 2

  • A single arrow

    ">" → 1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def steps_home(commands):
    pass

JavaScript

function stepsHome(commands) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →