SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Fall 2003
Prof. Doug Baldwin
CS faculty/student beginning-of-year party
Design a recursive algorithm that makes a robot draw an n-tile line and then go back to its original tile.
drawAndBack( n )
if n > 0
this.paint( color )
this.move()
this.drawAndBack( n - 1 )
this.move()
else
this.turnLeft()
this.turnLeft()
Paul, Caitlin, and Rich were demonstrating...
Suppose postconditions were different, robot facing in original direction
drawAndBack( n )
if n > 0
this.paint( color )
this.move()
this.drawAndBack( n - 1 )
this.turnLeft() // To turn robot from original direction to
this.turnLeft() // direction it has to move back in
this.move()
this.turnLeft() // To turn robot from backwards direction to
this.turnLeft() // original direction, for postcondition
else
// do nothing
this.turnLeft()
messages, the absence of statements in the base case) follow from considering
the problem's postcondition. Use the postcondition to help you think about
what your algorithm has to do before it can end, and what it has to work with
after a recursive message. Recursion as "black box" message(s) that solve some problem for you
Towers of Hanoi revisited
solve( n, source, destination, spare )
if ( n > 0 )
solve( n-1, source, spare, destination )
move( source, destination )
solve( n-1, spare, destination, source )
Explanation/dissection of this algorithm
How do you know it really always works?
Read Chapter 7 through Section 7.1.1
Mini-Assignment: Use induction to show that whenever n >= 4, n! > 2n