SUNY Geneseo Department of Computer Science


Recursion, Part 4

{Date}

CSci 141, Fall 2003
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Misc

CS faculty/student beginning-of-year party

Questions?

Drawing a Line

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...

[Waiting "Moves" Make Robot Return Along the Line It Painted]

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

Thinking Recursively

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

Next

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


Next Lecture