90 likes | 167 Views
More About Recursion. Java. Recall: A Towers Problem. Source Spare Target (coneFrom) (coneSpare) (coneTo). The challenge is to move all the disks from the source cone to the target cone. Move 1 disk at a time A larger disk may never be on top of a smaller disk.
E N D
More About Recursion Java
Recall: A Towers Problem Source Spare Target (coneFrom) (coneSpare) (coneTo) • The challenge is to move all the disks from the source cone to the target cone. • Move 1 disk at a time • A larger disk may never be on top of a smaller disk
The solution • To solve the towers problem, we need to know howmany disks we have and which cone is the source, the target, and the spare: towers Parameters: howmany, source, target, spare If howmany is equal to 1 move it (the smallest disk) from the source to the target Else Do in order call towers to move howmany-1 disks from source to spare (using target as spare) move it (disk # howmany) from the source to the target call towers to move howmany-1 disks from the spare to the target (using the source as the spare) base case – move 1 disk a smaller problem -- recursively move the rest of the disks Two recursive calls are used in this method.
Looking at recursion in Java • The idea is identical • A recursive call • One or more base cases
A sample problem • Building a bulls-eye on a picture • A bulls-eye is a series of concentric circles of alternating color Question: Should we build it from outside in, or from inside out?
Building a bulls-eye • Questions • How to draw a circle? • Use the Graphics method fillOval • We need to specify the upper left corner, and the width and height of the circle • What is the base case? • What is the recursive case? • How can we alternate colors?
// method in the Picture class public void drawBullsEye(){ int size = 100; int midx = 200; int midy = 200; Graphics g = this.getGraphics(); drawBull(g, size, midx, midy, true);}
private void drawBull(Graphics g, int diam, int x, int y, Boolean onOff) {if (onOff){ g.setColor(Color.black);}else{ g.setColor(Color.white);} if (diam >= 20){ g.fillOval(x - diam/2, y-diam/2, diam, diam); drawBull(g,diam-20,x,y,!onOff);} } // ends drawBull
Assignment • No reading assignment from Media Computation