SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Spring 2004
Prof. Doug Baldwin
Recursion = replacing "while" with "if"?
Recursion = defining something in terms of a smaller version of itself
Section 6.1
Recursion
Definition (see above)
to sing 99 bottles of beer song
sing verse for some number
sing song for next smaller number
unless number is 0, in which case
sing different verse
Lots of examples
take one step
take all remaining steps
Recursion in code
if ( ... some condition ... )
call yourself (repetition)
else
finish, do something simple
Sophisticated uses
A relatively sophisticated use of recursion, a preview of where recursion can get you.
Goal: Move an n-disk tower from one pole to another.
Rules:
See if you can...
The puzzle can actually be Solved in 4 lines of Java, using 2 recursions.
Draw a red line from the robot's current position to a wall.
public void lineToWall() {
this.paint( Color.red );
if ( this.okToMove() ) {
this.move();
this.lineToWall();
}
}
Count the tiles between robot's starting position (inclusive) and wall
public int countToWall( int count ) {
if ( this.okToMove() ) {
count = count + 1;
this.move();
this.countToWall( count );
}
return count;
}
Robot r = new Robot();
r.countToWall( 1 );
More Recursion
Mini-assignment: countToWall with no "count" parameter, variable, etc
Read Sections 6.2 through 6.5