2.3 Recursion do automated demo of towers of hanoi before class

Slides:



Advertisements
Similar presentations
Chapter 14 Recursion Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,, E. Reingold.
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright © Recursive GCD Demo public class.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
Towers of Hanoi
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
ITEC200 – Week07 Recursion. 2 Learning Objectives – Week07 Recursion (Ch 07) Students can: Design recursive algorithms to solve.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L10 (Chapter 19) Recursion.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Recursion Gordon College CPS212
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Unit 7 1 Unit 7: Recursion H Recursion is a fundamental programming technique that can provide an elegant solution to a certain kinds of problems H In.
1 Algorithm Design Techniques Greedy algorithms Divide and conquer Dynamic programming Randomized algorithms Backtracking.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
# 1# 1 VBA Recursion What is the “base case”? What is the programming stack? CS 105 Spring 2010.
Chapter 8 Recursion Modified.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Data Structures & Algorithms Recursion and Trees Richard Newman.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
1 Examples of Recursion Instructor: Mainak Chaudhuri
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion Continued Divide and Conquer Dynamic Programming.
Recursion Chapter What is recursion? Recursion occurs when a method calls itself, either directly or indirectly. Used to solve difficult, repetitive.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
APPLICATIONS OF RECURSION Copyright © 2006 Pearson Addison-Wesley. All rights reserved
Chapter 18 Recursion CS1: Java Programming Colorado State University
Chapter 14 Recursion.
Recursion.
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion Topic 5.
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion: The Mirrors
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Decrease-and-Conquer Approach
Chapter 15 Recursion.
Introduction to Computer Science - Alice
Chapter 12 Recursion (methods calling themselves)
2.3 Recursion do automated demo of towers of hanoi before class
Data Structures & Algorithms
Exam 2 Review 1.
Recursion Chapter 18.
The Hanoi Tower Problem
2.3 Recursion Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 2/17/11.
ITEC324 Principle of CS III
Presentation transcript:

2.3 Recursion do automated demo of towers of hanoi before class Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · April 10, 2017 8:13 tt

Reproductive Parts M. C. Escher, 1948 Overview What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations are naturally self-referential. Mergesort, FFT, gcd. Linked data structures. A folder contains files and other folders. Closely related to mathematical induction. Recursion and self reference are hugely important concepts in computer science and the natural world. (Perhaps a picture of a recursive tree or other object would be useful here) Escher. title = "Drawing Hands". We use title (Escher's reproductive parts) due to Bernard Chazelle. Also nice pic for circular linked list. Reproductive Parts M. C. Escher, 1948

Greatest Common Divisor Gcd. Find largest integer that evenly divides into p and q. Ex. gcd(4032, 1272) = 24. Applications. Simplify fractions: 1272/4032 = 53/168. RSA cryptosystem. 4032 = 26  32  71 1272 = 23  31  531 gcd = 23  31 = 24 How would you implement gcd?

Greatest Common Divisor Gcd. Find largest integer that evenly divides into p and q. Euclid's algorithm. [Euclid 300 BCE] base case reduction step, converges to base case gcd(4032, 1272) = gcd(1272, 216) = gcd(216, 192) = gcd(192, 24) = gcd(24, 0) = 24. Depiction from 1800's. Not much known about Euclid - spent time in Alexandria, Egypt. gcd = one of world's oldest algorithms 4032 = 3  1272 + 216

Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. base case reduction step, converges to base case p q q p % q x x x x x x x x gcd p = 8x q = 3x gcd(p, q) = x

Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. Java implementation. base case reduction step, converges to base case public static int gcd(int p, int q) { if (q == 0) return p; else return gcd(q, p % q); } base case reduction step

Recursive Graphics

Amazing hand-drawn image in NY Times by Serkan Ozkaya [Serkan Ozkaya] simply wanted to draw and see printed a faithful copy of all the type and pictures planned for a broadsheet page of this newspaper: this very page you are reading right now, which shows his version of the page you are reading right now, which shows his version of his version of the page you are reading right now, which...

Htree H-tree of order n. Draw an H. Recursively draw 4 H-trees of order n-1, one connected to each tip. and half the size tip size Application: distribute clock signal to endpoints on integrated circuit. Want distance from clock to each endpoint to be the same. Otherwise clock skew. order 1 order 2 order 3

Htree in Java public class Htree { public static void draw(int n, double sz, double x, double y) { if (n == 0) return; double x0 = x - sz/2, x1 = x + sz/2; double y0 = y - sz/2, y1 = y + sz/2; StdDraw.line(x0, y, x1, y); StdDraw.line(x0, y0, x0, y1); StdDraw.line(x1, y0, x1, y1); draw(n-1, sz/2, x0, y0); draw(n-1, sz/2, x0, y1); draw(n-1, sz/2, x1, y0); draw(n-1, sz/2, x1, y1); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); draw(n, .5, .5, .5); draw the H, centered on (x, y) recursively draw 4 half-size Hs

Animated H-tree Animated H-tree. Pause for 1 second after drawing each H. 20% 40% 60% 80% 100% do demo using AnimatedHtree.java - observe order in which H-tree pattern is drawn

Towers of Hanoi http://en.wikipedia.org/wiki/Image:Hanoiklein.jpg

Towers of Hanoi Move all the discs from the leftmost peg to the rightmost one. Only one disc may be moved at a time. A disc can be placed either on empty peg or on top of a larger disc. start finish Edouard Lucas invented Towers of Hanoi puzzle (1883) Lucas died as the result of a freak accident at a banquet when a plate was dropped and a piece flew up and cut his cheek. He died of erysipelas (rare skin infection) a few days later. Towers of Hanoi demo Edouard Lucas (1883)

Towers of Hanoi: Recursive Solution Move n-1 smallest discs right. Move largest disc left. cyclic wrap-around Consider the task of moving n discs from leftmost pole to rightmost pole. It is definitely the case that you need to transfer the biggest disc to the bottom of the rightmost pole, but you can't do that until all the remaining n-1 discs are removed from pole A. To get them out of the way, a good place to store them would be the middle pole. Once you have done this, you move the largest disc to pole C, and then transfer the rest of the discs from pole B to pole C. Move n-1 smallest discs right.

Towers of Hanoi Legend Q. Is world going to end (according to legend)? 64 golden discs on 3 diamond pegs. World ends when certain group of monks accomplish task. Q. Will computer algorithms help?

Towers of Hanoi: Recursive Solution public class TowersOfHanoi { public static void moves(int n, boolean left) { if (n == 0) return; moves(n-1, !left); if (left) System.out.println(n + " left"); else System.out.println(n + " right"); } public static void main(String[] args) { int N = Integer.parseInt(args[0]); moves(N, true); moves(n, true) : move discs 1 to n one pole to the left moves(n, false): move discs 1 to n one pole to the right smallest disc

Towers of Hanoi: Recursive Solution % java TowersOfHanoi 3 1 left 2 right 3 left % java TowersOfHanoi 4 1 right 2 left 3 right 4 left every other move is smallest disc subdivisions of ruler

Towers of Hanoi: Recursion Tree n, left 3, true 1 left 2 right 3 left 1 14 15 28 2, false 2, false 2 7 8 13 16 21 22 27 1, true 1, true 1, true 1, true 3 4 5 6 9 10 11 12 17 18 19 20 23 24 25 26

Towers of Hanoi: Properties of Solution Remarkable properties of recursive solution. Takes 2n - 1 moves to solve n disc problem. Sequence of discs is same as subdivisions of ruler. Every other move involves smallest disc. Recursive algorithm yields non-recursive solution! Alternate between two moves: move smallest disc to right if n is even make only legal move not involving smallest disc Recursive algorithm may reveal fate of world. Takes 585 billion years for n = 64 (at rate of 1 disc per second). Reassuring fact: any solution takes at least this long! to left if n is odd Perhaps a physicist would argue that it will take much longer for the world to end. 

Many important problems succumb to divide-and-conquer. Divide-and-conquer paradigm. Break up problem into smaller subproblems of same structure. Solve subproblems recursively using same method. Combine results to produce solution to original problem. Many important problems succumb to divide-and-conquer. FFT for signal processing. Parsers for programming languages. Multigrid methods for solving PDEs. Quicksort and mergesort for sorting. Hilbert curve for domain decomposition. Quad-tree for efficient N-body simulation. Midpoint displacement method for fractional Brownian motion. Divide et impera. Veni, vidi, vici. - Julius Caesar "Divide and conquer", Caesar's other famous quote "I came, I saw, I conquered" Divide-and-conquer idea dates back to Julius Caesar . (100 BCE - 44 BCE). Favorite war tactic was to divide an opposing army in two halves, and then assault one half with his entire force. Integer arithmetic for RSA cryptography. Adaptive quadrature for integration.

Fibonacci Numbers

Fibonacci Numbers and Nature pinecone http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fibnat.html Here is picture of an ordinary pinecone seen from its base where the stalk connects it to the tree. spirals in one direction, 13 in the other. Florets in cauliflower are organized in spirals around this centre in both directions. 5 in one direction, 8 in the other. Never think about cauliflower the same way! Lilies, irises, and the trillium have three petals; columbines, buttercups, larkspur, and wild rose have five petals; delphiniums, bloodroot, and cosmos have eight petals; corn marigolds have 13 petals; asters have 21 petals; and daisies have 34, 55, or 89 petals- cauliflower

Fibonacci Numbers Fibonacci numbers. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … L. P. Fibonacci (1170 - 1250) In 1225 Fibonacci took part in a tournament at Pisa ordered by the emperor himself, Frederick II. It was in just this type of competition that the following problem arose: Beginning with a single pair of rabbits, if every month each productive pair bears a new pair, which becomes productive when they are 1 month old, how many rabbits will there be after n months? Imagine that there are xn pairs of rabbits after n months. The number of pairs in month n+1 will be xn (in this problem, rabbits never die) plus the number of new pairs born. But new pairs are only born to pairs at least 1 month old, so there will be xn-1 new pairs. xn+1 = xn + xn-1 Don't want to think about the family tree! honeybee family tree: # of grandparents, great-grandparents are Fibonacci numbers (males have 1 parent, females have 2) Simplification: If a cow produces its first she-calf at age two years and after that produces another single she-calf every year, how many she-calves are there after 12 years, assuming none die? Fibonacci rabbits

A Possible Pitfall With Recursion Fibonacci numbers. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … A natural for recursion? FYI: classic math  = golden ratio  1.618 public static long F(int n) { if (n == 0) return 0; if (n == 1) return 1; return F(n-1) + F(n-2); } Virgil's Aeneid was analyzed at Princeton during the 1940s, and the proportions of lengths of paragraphs were close to the Golden Ratio. interesting formula since phi is irrational, and formula only involves power and square roots, yet gives integer for all integer values of n!

Recursion Challenge 1 (difficult but important) Q. Is this an efficient way to compute F(50)? A. No, no, no! This code is spectacularly inefficient. public static long F(int n) { if (n == 0) return 0; if (n == 1) return 1; return F(n-1) + F(n-2); } F(50) F(49) F(48) F(47) F(46) F(45) F(44) F(50) is called once. F(49) is called once. F(48) is called 2 times. F(47) is called 3 times. F(46) is called 5 times. F(45) is called 8 times. ... F(1) is called 12,586,269,025 times. recursion tree for naïve Fibonacci function Run Fibonacci.java for various values of n. Will we be able to compute F(50) before the end of class? F(51- i) is called F(i) times for i = 1..50.

Recursion Challenge 2 (easy and also important) Q. Is this an efficient way to compute F(50)? A. Yes. This code does it with 50 additions. Lesson. Don’t use recursion to engage in exponential waste. Context. This is a special case of an important programming technique known as dynamic programming (stay tuned). public static long(int n) { long[] F = new long[n+1]; F[0] = 0; F[1] = 1; for (int i = 2; i <= n; i++) F[i] = F[i-1] + F[i-2]; return F[n]; }

Summary How to write simple recursive programs? Base case, reduction step. Trace the execution of a recursive program. Use pictures. Why learn recursion? New mode of thinking. Powerful programming tool. Divide-and-conquer. Elegant solution to many important problems. Towers of Hanoi by W. A. Schloss. Towers of Hanoi = recursive music

Extra Slides

Fractional Brownian Motion

Fractional Brownian Motion Physical process which models many natural and artificial phenomenon. Price of stocks. Dispersion of ink flowing in water. Rugged shapes of mountains and clouds. Fractal landscapes and textures for computer graphics. continuous version of gambler's ruin problem or random walk

Simulating Brownian Motion Midpoint displacement method. Maintain an interval with endpoints (x0, y0) and (x1, y1). Divide the interval in half. Choose  at random from Gaussian distribution. Set xm = (x0 + x1)/2 and ym = (y0 + y1)/2 + . Recur on the left and right intervals. decreasing variance in each step by 2 makes it Brownian motion. If you change the scaling parameter e.g., to 4) you get fractional Brownian motion Note: this method of generating Brownian motion does not need to fix step size a priori (can zoom in indefinitely)

Simulating Brownian Motion: Java Implementation Midpoint displacement method. Maintain an interval with endpoints (x0, y0) and (x1, y1). Divide the interval in half. Choose  at random from Gaussian distribution. Set xm = (x0 + x1)/2 and ym = (y0 + y1)/2 + . Recur on the left and right intervals. public static void curve(double x0, double y0, double x1, double y1, double var) { if (x1 - x0 < 0.01) { StdDraw.line(x0, y0, x1, y1); return; } double xm = (x0 + x1) / 2; double ym = (y0 + y1) / 2; ym += StdRandom.gaussian(0, Math.sqrt(var)); curve(x0, y0, xm, ym, var/2); curve(xm, ym, x1, y1, var/2); Assume penDown() so that it traces the full path (must do left half before right half) variance halves at each level; change factor to get different shapes

Plasma Cloud Plasma cloud centered at (x, y) of size s. Each corner labeled with some grayscale value. Divide square into four quadrants. The grayscale of each new corner is the average of others. center: average of the four corners + random displacement others: average of two original corners Recur on the four quadrants. c1 c2 c3 c4

Plasma Cloud some artifacts parallel to x and y axes since it's not actually 2d Brownian motion - can use "diamond-square" algorithm to get 2d Brownian motion

Brownian Landscape Reference: http://www.geocities.com/aaron_torpy/gallery.htm

Brown Robert Brown (1773-1858)

Brownian Motion (Brown University Men’s Ultimate Frisbee Team)