Recursive Strategies Eric Roberts CS 106B January 23, 2013.

Slides:



Advertisements
Similar presentations
1 Line replacement approach Koch Star (Snowflake) Area replacement approach Sierpenski Triangle Iterated Function System approach Heighway Dragon CSE
Advertisements

Procedural Recursion Eric Roberts CS 106B April 15, 2009.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Lecture 12 Recursion part 1
Computer Science 111 Fundamentals of Programming I
Linear Interpolation Applying “weighted averages” to some graphics problems: animations and curve-drawing.
Laboratory Study II October, Java Programming Assignment  Write a program to calculate and output the distance traveled by a car on a tank of.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
LAB SESSION 7 Graphical user interface Applet fundamentals Methods in applets Execution of an applet Graphics class.
40S Applied Math Mr. Knight – Killarney School Slide 1 Unit: Sequences Lesson: SEQ-L3 Drawing Fractal Patterns Drawing Fractal Patterns Learning Outcome.
CompSci Today’s topics Java Recursion in Graphics Writing a Class Simple Animation Upcoming Simulation Reading Great Ideas, Chapters 5.
Four simple expressions in meta. Data objects Pieces of data in a computer are called objects Today, we’ll talk about four kinds of objects Numbers Pictures.
Recursion: Overview What is Recursion? Reasons to think recursively? An Example How does recursion work?
Four simple expressions in meta. Data objects Pieces of data in a computer are called objects Today, we’ll talk about four kinds of objects Numbers Pictures.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
CS 4731: Computer Graphics Lecture 5: Fractals Emmanuel Agu.
Holt Geometry 12-Ext Using Patterns to Generate Fractals 12-Ext Using Patterns to Generate Fractals Holt Geometry Lesson Presentation Lesson Presentation.
CS4395: Computer Graphics 1 Fractals Mohan Sridharan Based on slides created by Edward Angel.
Drawing pictures with Java. JFrame: the basic Java window The swing package contains classes, objects and methods that can be used to create a consistent.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
Approaches To Infinity. Fractals Self Similarity – They appear the same at every scale, no matter how much enlarged.
Mandelbrot Set the Who Is Mandelbrot?  Benoit Mandelbrot –Mandelbrot was born in Poland in He studied mathematics in France under Gaston Julia.
1 Excursions in Modern Mathematics Sixth Edition Peter Tannenbaum.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
Log on and Download from website:
Introduction Introduction: Mandelbrot Set. Fractal Geometry ~*Beautiful Mathematics*~ FRACTAL GEOMETRY Ms. Luxton.
Fractals Siobhán Rafferty.
Infinities 6 Iteration Number, Algebra and Geometry.
Ch 9 Infinity page 1CSC 367 Fractals (9.2) Self similar curves appear identical at every level of detail often created by recursively drawing lines.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Lecture 15: Intro to Graphics Yoni Fridman 7/25/01 7/25/01.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Backtracking and Games Eric Roberts CS 106B January 28, 2013.
1 Building Java Programs Supplement 3G: Graphics These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold,
{ Fractals, iterations and the Sierpinski Triangle an iterative approach Central Arizona College Science Night at San Tan Campus.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Koch Curve How to draw a Koch curve.. Start with a line segment (STAGE 0) *Divide the line into thirds *In the middle third produce an equilateral triangle.
Graphics Concepts CS 2302, Fall /17/20142 Drawing in Android.
Painting (Chapter 12) Java Certification Study Group January 25, 1999 Mark Roth.
CS324e - Elements of Graphics and Visualization Fractals and 3D Landscapes.
CS COMPUTER GRAPHICS LABORATORY. LIST OF EXPERIMENTS 1.Implementation of Bresenhams Algorithm – Line, Circle, Ellipse. 2.Implementation of Line,
 Introduction  Definition of a fractal  Special fractals: * The Mandelbrot set * The Koch snowflake * Sierpiński triangle  Fractals in nature  Conclusion.
Introduction to Graphics. Graphical objects To draw pictures, we will use three classes of objects: –DrawingPanel : A window on the screen. –Graphics.
1 Recursion. Objectives To define the concept of recursion as a programming strategy distinct from other forms of algorithmic decomposition. To recognize.
Visual C++ Programming: Concepts and Projects Chapter 10A: Recursion (Concepts)
Fractals Lesson 6-6.
Looking Ahead Eric Roberts CS 106A March 7, 2016.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 10A Recursion (Concepts)
Computer Science 111 Fundamentals of Programming I
Game Design, Development, and Technology
Iterative Mathematics
Computer Graphics Lecture 40 Fractals Taqdees A. Siddiqi edu
CS 1321.
Tuesday, January 22, 2013 Agenda: TISK & 2 MM Review HW answers
Chapter 8: Recursion Java Software Solutions
Recursion (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Chapter 8: Recursion Java Software Solutions
Chapter 14—Looking Ahead
Modeling with Geometry
Tree Rotations and AVL Trees
slides courtesy of Eric Roberts
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

Recursive Strategies Eric Roberts CS 106B January 23, 2013

Recursion One of the most important Great Ideas in CS 106B is the concept of recursion, which is the process of solving a problem by dividing it into smaller subproblems of the same form. The italicized phrase is the essential characteristic of recursion; without it, all you have is a description of stepwise refinement of the sort we teach in CS 106A. The fact that recursive decomposition generates subproblems that have the same form as the original problem means that recursive programs will use the same function or method to solve subproblems at different levels of the solution. In terms of the structure of the code, the defining characteristic of recursion is having functions that call themselves, directly or indirectly, as the decomposition process proceeds.

A Simple Illustration of Recursion Suppose that you are the national fundraising director for a charitable organization and need to raise $1,000,000. One possible approach is to find a wealthy donor and ask for a single $1,000,000 contribution. The problem with that strategy is that individuals with the necessary combination of means and generosity are difficult to find. Donors are much more likely to make contributions in the $100 range. Another strategy would be to ask 10,000 friends for $100 each. Unfortunately, most of us dont have 10,000 friends. There are, however, more promising strategies. You could, for example, find ten regional coordinators and charge each one with raising $100,000. Those regional coordinators could in turn delegate the task to local coordinators, each with a goal of $10,000, continuing the process reached a manageable contribution level.

A Simple Illustration of Recursion The following diagram illustrates the recursive strategy for raising $1,000,000 described on the previous slide: Goal: $1,000,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $100,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $10,000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $1000 Goal: $100 Goal: $100 Goal: $100 Goal: $100 Goal: $100 Goal: $100 Goal: $100 Goal: $100 Goal: $100 Goal: $100

A Pseudocode Fundraising Strategy If you were to implement the fundraising strategy in the form of a C++ function, it would look something like this: void collectContributions(int n) { if (n <= 100) { Collect the money from a single donor. } else { Find 10 volunteers. Get each volunteer to collect n/10 dollars. Combine the money raised by the volunteers. } What makes this strategy recursive is that the line Get each volunteer to collect n/10 dollars. will be implemented using the following recursive call: collectContributions(n / 10);

Suggestions for Improvement More candy. We need to get more candy to our students.Problem: Solution:Use the magic of recursion. Strategy:Run the money tree example in reverse. In the suggestions that came in as part of the Assignment #1 messages, the most consistent suggestion was to videotape the class. As I mentioned on the first day of class, there are no funds available to do so. There was, however, another suggestion that several of you put forward:

The Towers of Hanoi In the great temple at Benares beneath the dome which marks the center of the world, rests a brass plate in which are fixed three diamond needles, each a cubit high and as thick as the body of a bee. On one of these needles, at the creation, God placed sixty-four disks of pure gold, the largest disk resting on the brass plate and the others getting smaller and smaller up to the top one. This is the Tower of Brahma. Day and night unceasingly, the priests transfer the disks from one diamond needle to another according to the fixed and immutable laws of Brahma, which require that the priest on duty must not move more than one disk at a time and that he must place this disk on a needle so that there is no smaller disk below it. When all the sixty-four disks shall have been thus transferred from the needle on which at the creation God placed them to one of the other needles, tower, temple and Brahmins alike will crumble into dust, and with a thunderclap the world will vanish. Henri de Parville, La Nature, 1883

The Towers of Hanoi Solution Hanoi skip simulation int main() { int nDisks = 3; initHanoiGraphics(nDisks); moveTower(nDisks, 'A', 'B', 'C'); return 0; } nDisks 3 void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'A''B' n 3 temp 'C' void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'A''C' n 2 temp 'B' void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'A''B' n 1 temp 'C' void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'B''C' n 1 temp 'A' void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'C''B' n 2 temp 'A' void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'C''A' n 1 temp 'B' void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'A''B' n 1 temp 'C' int main() { int nDisks = 3; initHanoiGraphics(nDisks); moveTower(nDisks, 'A', 'B', 'C'); return 0; } void moveTower(int n, char start, char finish, char temp) { if (n == 1) { moveSingleDisk(start, finish); } else { moveTower(n - 1, start, temp, finish); moveSingleDisk(start, finish); moveTower(n - 1, temp, finish, start); } startfinish 'A''B' n 3 temp 'C'

The Recursive Leap of Faith The purpose of going through the complete decomposition of the Towers of Hanoi problem is to convince you that the process works and that recursive calls are in fact no different from other method calls, at least in their internal operation. The danger with going through these details is that it might encourage you to do the same when you write your own recursive programs. As it happens, tracing through the details of a recursive program almost always makes such programs harder to write. Writing recursive programs becomes natural only after you have enough confidence in the process that you dont need to trace them fully. As you write a recursive program, it is important to believe that any recursive call will return the correct answer as long as the arguments define a simpler subproblem. Believing that to be trueeven before you have completed the codeis called the recursive leap of faith.

The Recursive Paradigm Most recursive functions you encounter in an introductory course have bodies that fit the following general pattern: if ( test for a simple case ) { Compute and return the simple solution without using recursion. } else { Divide the problem into one or more subproblems that have the same form. Solve each of the problems by calling this method recursively. Return the solution from the results of the various subproblems. } Finding a recursive solution is mostly a matter of figuring out how to break it down so that it fits the paradigm. When you do so, you must do two things: Identify simple cases that can be solved without recursion.1. Find a recursive decomposition that breaks each instance of the problem into simpler subproblems of the same type, which you can then solve by applying the method recursively. 2.

Generating Mondrian-Style Paintings Fig. 11: Three real Mondrian paintings, and three samples from our targeting function. Can you tell which is which? Source: Jerry O. Talton, Yu Lou, Steve Lesser, Jared Duke, Radomír Měch, and Vladlen Koltun, Metropolis Procedural Modeling, ACM Transactions on Graphics, April 2011.

Generating Mondrian-Style Paintings Just to preserve it for posterity, here is the Mondrian Style candy plaque presented for guessing which paintings were real:

Mondrian Decomposition

Methods in the Graphics Library GWindow gw( width, height ) Creates a graphics window with the specified dimensions. gw.drawLine( x 0, y 0, x 1, y 1 ) Draws a line connecting the points (x 0, y 0 ) and (x 1, y 1 ). gw.drawPolarLine( x 0, y 0, r, theta ) Draws a line r pixels long in direction theta from (x 0, y 0 ). To make chaining line segments easier, this function returns the ending coordinates as a GPoint. gw.getWidth() Returns the width of the graphics window. gw.getHeight() Returns the height of the graphics window. Many more functions exist in the gwindow.h and gobjects.h interfaces. The full documentation is available on the web site.

#include #include "gwindow.h" #include "random.h" using namespace std; /* Constants */ const double MIN_AREA = 10000; /* Smallest square that will be split */ const double MIN_EDGE = 20; /* Smallest edge length allowed */ /* Function prototypes */ void subdivideCanvas(GWindow & gw, double x, double y, double width, double height); /* Main program */ int main() { GWindow gw; subdivideCanvas(gw, 0, 0, gw.getWidth(), gw.getHeight()); return 0; } Code for the Mondrian Program Page 1 of 2

#include #include "gwindow.h" #include "random.h" using namespace std; /* Constants */ const double MIN_AREA = 10000; /* Smallest square that will be split */ const double MIN_EDGE = 20; /* Smallest edge length allowed */ /* Function prototypes */ void subdivideCanvas(GWindow & gw, double x, double y, double width, double height); /* Main program */ int main() { GWindow gw; subdivideCanvas(gw, 0, 0, gw.getWidth(), gw.getHeight()); return 0; } void subdivideCanvas(GWindow & gw, double x, double y, double width, double height) { if (width * height >= MIN_AREA) { if (width > height) { double mid = randomReal(MIN_EDGE, width - MIN_EDGE); subdivideCanvas(gw, x, y, mid, height); subdivideCanvas(gw, x + mid, y, width - mid, height); gw.drawLine(x + mid, y, x + mid, y + height); } else { double mid = randomReal(MIN_EDGE, height - MIN_EDGE); subdivideCanvas(gw, x, y, width, mid); subdivideCanvas(gw, x, y + mid, width, height - mid); gw.drawLine(x, y + mid, x + width, y + mid); } Code for the Mondrian Program Page 2 of 2

Exercise: A Better Mondrian Program Can you do a better job of emulating Mondrians style? Suppose that you have the following additional functions: gw.drawRect( x, y, width, height ) Draws the outline of a rectangle with the specified bounds. gw.fillRect( x, y, width, height ) Fills the outline of the specified rectangle using the current color. gw.setColor( color ) Sets the pen color to the specified color string (such as "BLACK" or "RED" ) gw.setColor("# rrggbb ") Sets the red/green/blue components to the specified hexadecimal values.

Revised Mondrian Decomposition

Recursion and Fractals Recursion comes up in other graphical applications, most notably in the creation of fractals, which are mathematical structures consisting of similar figures at various different scales. Fractals were popularized in a 1982 book by the late Benoit Mandelbrot entitled The Fractal Geometry of Nature. One of the simplest fractal patterns to draw is the Koch fractal, named after its inventor, the Swedish mathematician Helge von Koch ( ). The Koch fractal is sometimes called a snowflake fractal because of the beautiful, six-sided symmetries it displays as the figure becomes more detailed. as illustrated in the following diagram:

How Long is the Coast of England? The first widely circulated paper about fractals was a 1967 article in Science by Mandelbrot that asked the seemingly innocuous question, How long is the coast of England? The point that Mandelbrot made in the article is that the answer depends on the measurement scale, as these images from Wikipedia show. This thought-experiment serves to illustrate the fact that coastlines are fractal in that they exhibit the same structure at every level of detail. 200km ruler100km ruler50km ruler

Exercise: Fractal Coastline Coastline Exercise 15 on page 384 asks you to draw a fractal coastline between two points, A and B, on the graphics window. –The order-0 coastline is just a straight line. –The order-1 coastline replaces that line with one containing a triangular wedge pointing randomly up or down. –The order-2 coastline does the same for each line in the order-1. –Repeating this process eventually yields an order-5 coastline.

The End