Scala Tutorial Through Katas: Mars Rover (Medium)

A programming kata is an exercise which helps a programmer hone his skills through practice and repetition.

This article is part of the series "Scala Tutorial Through Katas". Articles are divided into easy, medium and hard. Beginners should start with easy ones and move towards more complicated once they feel more comfortable programming in Scala.

For the complete list of Scala katas and solutions please visit the index page

The article assumes that the reader is familiar with the basic usage of ScalaTest asserts and knows how to run them from his favorite Scala IDE (ours is IntelliJ IDEA with the Scala plugin).

Tests that prove that the solution is correct are displayed below. Recommended way to solve this kata is to write the implementation for the first test, confirm that it passes and move to the next. Once all of the tests pass, the kata can be considered solved.

One possible solution is provided below the tests. Try to solve the kata by yourself first.

Mars Rover

Develop an api that moves a rover around on a grid.

  • You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing.
  • The rover receives a character array of commands.
  • Implement commands that move the rover forward/backward (f,b).
  • Implement commands that turn the rover left/right (l,r).
  • Implement wrapping from one edge of the grid to another. (planets are spheres after all)
  • Implement obstacle detection before each move to a new square. If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle.

Following is a set of unit tests that can be used to solve this kata in the TDD fashion.

[UNIT TESTS]

Test code can be found in the GitHub MarsRover.scala.

[ONE POSSIBLE SOLUTION]

The solution code can be found in MarsRover.scala solution.

Alternative (and better) solution done by Nishruu can be found here.

What was your solution? Post it as a comment so that we can compare different ways to solve this kata.

2 thoughts on “Scala Tutorial Through Katas: Mars Rover (Medium)

    1. Viktor Farcic

      Let’s say that the planet grid is 5×5 and the rover is on the position 4×2 facing east. Command ‘f’ would take it to the position 5×2. Another command ‘f’ would end with the location 1×2. Since the grid is 5×5, rover cannot be on the position 6×2.

      Reply

Leave a Reply