University of California, Berkeley
EECS Department - Computer Science Division

CS3 Lecture 23 : Recursion Potpourri


Overview of today's lecture


Answers to questions that have come up

Project Questions

Review

Fractals


Recursion Potpourri

Overview

Randomized Sierpinski Triangle

;; randomized-sierpinski-triangle
;; by Clint Ryan
;; (we've hardcoded the vertex locations in)
;;
(define (randomized-sierpinski-triangle n)
  (clear-graphics)
  (rst-helper n -200 -200))

(define (rst-helper n x y)
  (draw-point x y)
  (if (zero? n) 'wow
    (let ((vert (random 3)))
      (cond
        ((= 0 vert)
         (rst-helper (- n 1) (/ (+ x -200) 2)(/ (+ y  -200) 2)))
        ((= 1 vert)
         (rst-helper (- n 1) (/ (+ x  200) 2) (/ (+ y -200) 2)))
        ((= 2 vert)
         (rst-helper (- n 1) (/ (+ x    0) 2) (/ (+ y  200) 2)))))))

Fibonacci revisited

(define (fib n)
   (if (<= n 2)
       1
       (+ (fib (- n 1))
          (fib (- n 2)))))

Tower of Hanoi

Background

How to solve this puzzle

;; As we recurse the pegs will be changing
;; (what we start at may be our prior end peg), 
;; so we will use peg names as parameters.

(define (hanoi num start extra end)
  (cond ((zero? num) 'done)
        (else
          (hanoi (- num 1) start end extra)
          (display
            `(move disk ,num from peg ,start to peg ,end))
          (newline)
          (hanoi (- num 1) extra start end))))

: (hanoi 3 'a 'b 'c)
(move disk 1 from peg a to peg c)
(move disk 2 from peg a to peg b)
(move disk 1 from peg c to peg b)
(move disk 3 from peg a to peg c)
(move disk 1 from peg b to peg a)
(move disk 2 from peg b to peg c)
(move disk 1 from peg a to peg c)
done

Hand trace

(hanoi 3 'a 'b 'c)
    (hanoi 2 'a 'c 'b)
        (hanoi 1 'a 'b 'c)
            (hanoi 0 'a 'c 'b)
            done
            (move disk 1 from peg a to peg c)
            (hanoi 0 'b 'a 'c)
            done
        done
        (move disk 2 from peg a to peg b)
        (hanoi 1 'c 'a 'b)
            (hanoi 0 'c 'b 'a)
            done
            (move disk 1 from peg c to peg b)
            (hanoi 0 'a 'c 'b)
            done
        done
    done
    (move disk 3 from peg a to peg c)
    (hanoi 2 'b 'a 'c)
        (hanoi 1 'b 'c 'a)
            (hanoi 0 'b 'a 'c)
            done
            (move disk 1 from peg b to peg a)
            (hanoi 0 'c 'b 'a)
            done
        done
        (move disk 2 from peg b to peg c)
        (hanoi 1 'a 'b 'c)
            (hanoi 0 'a 'c 'b)
            done
            (move disk 1 from peg a to peg c)
            (hanoi 0 'b 'a 'c)
            done
        done
    done
done

Animation (using the Grillmeyer Scheme...)


Summary

Next Time

Puzzle : Fair Event from Unfair Coin

Game : Amazons