RECURSION: An Introduction
In today's lab, we will explore the power of recursion.
Part I: Consider the following applet that draws
a sequence of rectangles.
//
A basic extension of the java.applet.Applet class
import
java.awt.*;
import
java.applet.*;
public
class Applet1 extends Applet
{
public void init() {
setLayout(null);
setSize(600,600);
}
public void paint(Graphics g){
setBackground(Color.yellow);
drawPattern(g, 10, 10, 270);
}
void drawPattern(Graphics g, int x, int y, int s ){
// note that x and y are the coordinates of the upper-left corner of our
// square (as measured from the upper-left corner of our window).
// s denotes the length of the side of our square
if ((s > 1)){
g.setColor(Color.blue);
g.drawLine(x,y,x+s,y);
g.drawLine(x,y+s, x+s,y+s);
g.drawLine(x,y,x,y+s);
g.drawLine(x+s,y,x+s,y+s);
g.fillRect(x , y+2*s/3, s/3, s/3);
drawPattern(g, x+s/3, y, 2*s/3); // here is our recursive step
}
}
}
Run this applet. Explore what happens if the (s>1) condition is
changed to (s>5). How does this condition control the depth
of recursion?
Part II: A word is said to be a palindrome
if the "reverse" of the word is identical to the original word. For
example: madam, abcdefgfedcba,
and I are each palindromes. Write
and test a recursive Java method,
public
static boolean isPalindrome(char[] A, int firstIndex, int lastIndex),
which determines if a sequence of characters stored in an array
A, from indices firstIndex to lastIndex, is actually a palindrome. (You
may either "wire-in" the values stored by the array in the client, or use
a method similar to that of your DNA assignment to read in the word.)
Part III: Recall the famous combinatorial identity discussed in class:
C(n,r) = C(n-1, r) + C(n-1, r-1).
Part IV: Here is a more geometrically interesting applet.
//
A basic extension of the java.applet.Applet class
import
java.awt.*;
import
java.applet.*;
public
class Applet1 extends Applet
{
public void init() {
setLayout(null);
setSize(600,600);
}
public void paint(Graphics g){
setBackground(Color.black);
g.setColor(Color.green);
drawBoxes(g, 150, 125, 125, 'c');
}
void drawBoxes(Graphics g, int x, int y, int s, char loc){
if (s>0){
g.drawOval(x, y, s, s);
g.setColor(Color.magenta);
if (loc!='s'){
drawBoxes(g, x+s/4, y-s/2, s/2, 'n');
}
g.setColor(Color.yellow);
if (loc!='w')
drawBoxes(g, x+s, y+s/4, s/2, 'e');
g.setColor(Color.blue);
if (loc!='n')
drawBoxes(g, x+s/4, y+s, s/2, 's');
g.setColor(Color.green);
if (loc!='e')
drawBoxes(g, x-s/2, y+s/4, s/2, 'w');
}
}
}
Try to understand how this recursive code performs. Try
modifying it to obtain your own patterns, using rectangles, ovals, or triangles.