Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Finding a non-recursive algorithm

807607Dec 17 2006 — edited Dec 20 2006
I had a project a year ago that was supposed to teach the class recursion. Already being familiar with the Java language, the project was simple.

The project was, you ahve a "cleaning robot" which cleans an entire room and then returns to the spot it originally was. The room was inputed as a txt file. Everytime you moved to a spot it was automatically cleaned

The Robot was given to you. The robot class hasthe following methods:
void move(Direction)   - moves in the direction you gave it.
boolean canMove(Direction)    -  returns true if the robot can move there without running into a wall
boolean hasBeen(Direction) - returns true if the robot has cleaned the spot that is in that direction
The Direction class was given to you. It is an enumerated type with the Directions FORWARD, BACWARD, LEFT, RIGHT.

now the Recursive algorithm is simple:
private void clean(Direction c, Direction r) 
{
   		move(c); //clean spot in direction
   		for(Direction d : Direction.values()) //go every direction
   			if(canMove(d) && !haveBeen(d)) clean(d,reverse(d)); 
   		move(r); //go back way we came 
}

private Direction reverse(Direction d)
 {
			switch(d)
			{
   			case FORWARD:  d = Direction.BACKWARD; break;
   			case RIGHT:    d = Direction.LEFT;     break;
   			case BACKWARD: d = Direction.FORWARD;  break;
   			case LEFT:     d = Direction.RIGHT;    break;
   		}
   		return d;	 
 }

public void start()
    {
    	clean(Direction.FORWARD, Direction.BACKWARD);
    }
But I am curious how someone would go about implementing a NON recursive algorithm. I understand it would probably be around 2000 lines to implement it. I am not asking anyone to implement it, nor do I plan on it (well..I may one day if I am bored) I am only asking for mere curiosity how someone would go about implementing this non-recursively.

I have thought about it and thought about it, and the only thing I come up with is recursion. What are your thoughts?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 17 2007
Added on Dec 17 2006
5 comments
412 views