home

Mars Rover in Java

June 6, 2010 · 9 comments

Sometime back, when Arun posted a Python version of Mars Rover problem, I tried the same in Java. Btw, if you haven’t heard about Mars Rover problem before, here’s the text for you (Ctrl+C & Ctrl+V’ed from Arun’s post).

Mars Rover problem:

A squad of robotic rovers are to be landed by NASA on a plateau on Mars.

This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.

A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

INPUT:

The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.

The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover’s position, and the second line is a series of instructions telling the rover how to explore the plateau.

The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover’s orientation.

Each rover will be finished sequentially, which means that the second rover won’t start to move until the first one has finished moving.

OUTPUT:

The output for each rover should be its final co-ordinates and heading.

INPUT AND OUTPUT

Test Input:

5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

Expected Output:

1 3 N
5 1 E

Solution in Java:

package marsrover;
public class Rover {
	public static final Integer N = 1;
	public static final Integer E = 2;
	public static final Integer S = 3;
	public static final Integer W = 4;
	Integer x = 0;
	Integer y = 0;
	Integer facing = N;
	public Rover() {
	}
	public void setPosition(Integer x, Integer y, Integer facing) {
		this.x = x;
		this.y = y;
		this.facing = facing;
	}
	public void printPosition() {
		char dir = 'N';
		if (facing == 1) {
			dir = 'N';
		} else if (facing == 2) {
			dir = 'E';
		} else if (facing == 3) {
			dir = 'S';
		} else if (facing == 4) {
			dir = 'W';
		}
		System.out.println(x + " " + y + " " + dir);
	}
	public void process(String commands) {
		for (int idx = 0; idx < commands.length(); idx++) {
			process(commands.charAt(idx));
		}
	}
	private void process(Character command) {
		if (command.equals('L')) {
			turnLeft();
		} else if (command.equals('R')) {
			turnRight();
		} else if (command.equals('M')) {
			move();
		} else {
			throw new IllegalArgumentException(
					"Speak in Mars language, please!");
		}
	}
	private void move() {
		if (facing == N) {
			this.y++;
		} else if (facing == E) {
			this.x++;
		} else if (facing == S) {
			this.y--;
		} else if (facing == W) {
			this.x--;
		}
	}
	private void turnLeft() {
		facing = (facing - 1) < N ? W : facing - 1;
	}
	private void turnRight() {
		facing = (facing + 1) > W ? N : facing + 1;
	}
	public static void main(String args[]) {
		Rover rover = new Rover();
		rover.setPosition(1, 2, N);
		rover.process("LMLMLMLMM");
		rover.printPosition(); // prints 1 3 N
		rover.setPosition(3, 3, E);
		rover.process("MMRMMRMRRM");
		rover.printPosition(); // prints 5 1 E
	}
}

After comparing my version with Arun’s version, all it came to my mind was, Joe Armstrong’s this quote:

“The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.”

Become java expert with testking N10-004 web development course. Download the testking 640-822 videos and testking 642-813 study guides to learn java applications for the web.

Related Posts

{ 9 comments… read them below or add one }

Ken June 17, 2010 at 1:11 AM
public class Rover {
    int x,y,d;
    public static final int W=0, S=1, E=2, N=3;
    char[] dirs = {'W', 'S', 'E',  'N'};

    public Rover(int x, int y, int d){
        this.x=x; this.y=y; this.d=d;
    }

    public static void main( String[] args){
        new Rover(1, 2, N).act("LMLMLMLMM");
        new Rover(3, 3, E).act("MMRMMRMRRM");
    }

    void act(String acts){
        for (int idx = 0; idx < acts.length(); idx++)
           process(acts.charAt(idx));
        System.out.println(x + " " + y + " " + dirs[d]);
    }

    void process(char c){
        switch(c){
            case 'L': d = (d+1) % 4 ;break;
            case 'R': d = (d==0?4:d) - 1; break;
            default: if(d%2==0) x+=(d-1);  else y+=(d-2);
        }
    }
}

Reply

Veera June 17, 2010 at 7:12 AM

good one!

Reply

Wang June 17, 2010 at 11:53 AM

inlining process() will save two more lines.

Reply

Somebody June 17, 2010 at 12:06 PM

Three

Reply

Bhuvaness September 23, 2010 at 6:23 PM

VEERA,

Is this solution is accepted by TW.

Reply

Veera September 23, 2010 at 8:33 PM

Sorry, what is TW?

Reply

Varsha Chougule. August 21, 2011 at 2:26 PM

/* Solution for mars rovers problem in c */
#include
#include
#include
#include
int main(void)
{
/* request auto detection */
int gd= DETECT, gm;
int x=100, y=100;
int i,j,k,r,c,ix,iy,X,Y,XX,YY,s;
char d,str[20];
clrscr();
initgraph(&gd,&gm,”c:\\tc2\\bgi”);
printf(“enter no of rows and cols”);
scanf(“%d%d”,&r,&c);
for(i=0;i<=r;i++)
{
line(x,y+i*50,x+c*50,y+i*50);
Y=y+i*50;
}
for(i=0;i<=c;i++)
{
line(x+i*50,y,x+i*50,y+r*50);
X=x;
}
printf("\n %d %d",X,Y);
printf("enter initial position");
scanf("%d%d",&ix,&iy);
printf("char");
cscanf("%c",&d);
XX=X+(ix*50)-25;
YY=Y-(iy*50)+25;
switch(d)
{ case 'n':
outtextxy(XX,YY,"^");
break;
case 's':
outtextxy(XX,YY,"V");
break;
case 'w':
outtextxy(XX,YY,"”);
break;
}
printf(“enter string”);
scanf(” %s”,str);
for(i=0;str[i]!=”;i++)
{
if(str[i]==’m')
{
if(d==’e')
XX=XX+50;
if(d==’w')
XX=XX-50;
if(d==’n')
YY=YY-50;
if(d==’s')
YY=YY+50;
}
if(str[i]==’l')
{
if(d==’e')
d=’n';
else if(d==’w')
d=’s';
else if(d==’n')
d=’w';
else if(d==’s')
d=’e';
}
if(str[i]==’r')
{
if(d==’e')
d=’s';
else if(d==’w')
d=’n';
else if(d==’n')
d=’e';
else if(d==’s')
d=’w';
}
}
switch(d)
{ case ‘n’:
outtextxy(XX,YY,”^”);
break;
case ‘s’:
outtextxy(XX,YY,”V”);
break;
case ‘w’:
outtextxy(XX,YY,”");
break;
}
ix=(XX+25-X)/50;
iy=(Y+25-YY)/50;
printf(” %d %d %c”,ix,iy,d);
getch();
}

Reply

Arun September 15, 2011 at 4:34 AM
Some October 18, 2011 at 11:40 PM

public class Rover {
int x,y,d;
public static final int W=0, S=1, E=2, N=3;
char[] dirs = {‘W’, ‘S’, ‘E’, ‘N’};

public Rover(int x, int y, int d){
this.x=x; this.y=y; this.d=d;
}

public static void main( String[] args){
new Rover(1, 2, N).act(“LMLMLMLMM”);
new Rover(3, 3, E).act(“MMRMMRMRRM”);
}

void act(String acts){
for (int idx = 0; idx < acts.length(); idx++)
switch(acts.charAt(idx)){
case 'L': d = (d+1) % 4 ;break;
case 'R': d = (d==0?4:d) – 1; break;
case: if(d%2==0) x+=(d-1); else y+=(d-2);
}
System.out.println(x + " " + y + " " + dirs[d]);
}
}

Reply

Leave a Comment

Previous post:

Next post: