RECURSION II CITS1001. 2 Scope of this lecture Recursive data structures/objects Combinations.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

CHAPTER 2 ALGORITHM ANALYSIS 【 Definition 】 An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition,
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
Iteration and Recursion Tonga Institute of Higher Education.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Finding the Median Algorithm : Design & Analysis [11]
CS 206 Introduction to Computer Science II 10 / 01 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 02 / 25 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
 To be able to write larger programs ◦ By breaking them down into smaller parts and passing data between the parts.  To understand the concepts of Methods.
BUILDING JAVA PROGRAMS CHAPTER 7 Array Algorithms.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Object Oriented Software Development
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Tree.
Methods and You. Up to this point, I have covered many different data types with you. Variables can be considered the nouns of an English sentence. If.
Thought for the Day “To become truly great, one has to stand with people, not above them.” – Charles de Montesquieu.
M180: Data Structures & Algorithms in Java
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
COMP Recursion, Searching, and Selection Yi Hong June 12, 2015.
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Dynamic Programming. Algorithm Design Techniques We will cover in this class: ◦ Greedy Algorithms ◦ Divide and Conquer Algorithms ◦ Dynamic Programming.
CS 206 Introduction to Computer Science II 02 / 23 / 2009 Instructor: Michael Eckmann.
CS 361 – Chapters 8-9 Sorting algorithms –Selection, insertion, bubble, “swap” –Merge, quick, stooge –Counting, bucket, radix How to select the n-th largest/smallest.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Recursion Pepper. Another way to loop Call yourself repeatedly until you say to stop. Example: add up 10 numbers using addUp. -- Input – number to count.
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.
Building Java Programs Binary Trees reading: 17.1 – 17.3.
CSE 143 Lecture 10 Recursion reading: slides created by Marty Stepp and Hélène Martin
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Question of the Day  What three letter word completes the first word and starts the second one: DON???CAR.
1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Data Structure and Algorithms
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
CSE 143 Lecture 9 Recursion slides created by Alyssa Harding
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
CS 106 Introduction to Computer Science I 10 / 10 / 2007 Instructor: Michael Eckmann.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
CSE 143 Lecture 9: introduction to recursion reading: 12.1.
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Recursion.
Java 4/4/2017 Recursion.
Recursion CITS1001.
slides adapted from Marty Stepp and Hélène Martin
Chapter 12 Recursion (methods calling themselves)
slides created by Marty Stepp and Alyssa Harding
Week 4 Lecture-2 Chapter 6 (Methods).
Java Programming: Chapter 9: Recursion Second Edition
Flowcharts and Pseudo Code
Building Java Programs
slides adapted from Marty Stepp and Hélène Martin
ITI Introduction to Computing II Lab-12
Dr. Sampath Jayarathna Cal Poly Pomona
slides created by Marty Stepp
Recursion.
Lecture 20 – Practice Exercises 4
Lecture 6 - Recursion.
Presentation transcript:

RECURSION II CITS1001

2 Scope of this lecture Recursive data structures/objects Combinations

Employee data Consider a class that describes the hierarchical structure of a company Each person is an employee Some employees supervise other employees Who might supervise other employees… This has a natural recursive structure How do we represent this in Java? 3

Employee data includes Employee public class Employee { private int IDnumber; private Employee supervisor; private Employee[] staff; } Every person in the company is an employee Every person has a supervisor(?) Every person has zero or more underlings that they manage directly Each of those underlings is an employee, with a supervisor and underlings… 4

An organisational chart 5 Alf BettyCharlesDiane GeorgeFredEthelHilaryImogen LucyKeithJack MarkNora

Every person in the company is represented by an Employee object Employee objects 6 supervisor = null staff[0] = Betty staff[1] = Charles staff[2] = Diane Alf supervisor = Alf staff[0] = Ethel staff[1] = Fred Betty supervisor = Lucy staff = null Mark

Employee ranks Every person in the company has a title, which reflects their standing relative to other people in the company public String title() { if (supervisor == null) return “President”; else return “Vice-” + supervisor.title(); } 7

Cascading method calls 8 Alf.title() returns “President” Betty.title()returns “Vice-” + Alf.title() which is “Vice-President” Mark.title()returns “Vice-”+Lucy.title() which is “Vice-”+”Vice-”+Hilary.title() which is “Vice-”+”Vice-”+”Vice-”+Diane.title() which is “Vice-”+”Vice-”+”Vice-”+”Vice-”+Alf.title() which is “Vice-Vice-Vice-Vice-President”

“Pass the buck” 9 In this situation, most method calls are achieved by simply “passing the buck” i.e. asking another object to perform some calculation Consider the problem of Alf trying to find out how many subordinates he has Staff, staff-of-staff, staff-of-staff-of-staff, etc. The “pass the buck” method is to Ask Betty how many subordinates she has Ask Charles how many subordinates he has Ask Diane how many subordinates she has Add those numbers together, and add three (for Betty, Charles, and Diane themselves)

The buck stops here All recursion needs a base case, which stops the recursion and returns a result directly In this case, it’ll stop at the bottom of the organisation Someone with no underlings can just return 0 E.g. Ethel, Jack, Keith, etc. 10

In Java public int subordinateCount() { if (staff == null) return 0; else { int num = 0; for (Employee e : staff) num += 1 + e.subordinateCount(); return num; } 11

Method structure follows data structure In both of these methods, the structure of the data dictates the structure of the code subordinateCount recurses down the hierarchy Every path going down contributes to the result title recurses up the hierarchy The single path back to the root (Alf!) builds the result Many, many algorithms traverse trees of data in this way This “data structure implies code structure” pattern is much like how a 1D array implies the use of for loops and foreach loops 12

Combinations Another common use of recursion is in enumerating combinations of possibilities Consider partitioning a positive integer n into a sum of smaller positive integers For example 4 could be partitioned in five ways How many distinct ways can we do this for n? 13

Partitions of n Ultimately we want a method with the following signature // list all ways of partitioning n into numbers public static void listPartitions(int n) 14

Partitions of n into two numbers Let’s start with a method that lists all partitions of n into exactly two numbers, e.g. for We only want partitions where the numbers are in ascending order, otherwise we will generate duplicates // list all ways of partitioning n into two numbers public static void listParts2(int n) { for (int i = 1; i <= n / 2; i++) System.out.println(i + " + " + (n - i)); } 15

Now consider partitions of n into exactly three numbers, e.g. for // list all ways of partitioning n into three numbers public static void listParts3(int n) { for (int i = 1; i <= n / 3; i++) for (int j = i; j <= (n - i) / 2; j++) System.out.println(i + " + " + j + " + " + (n-i-j)); } Partitions of n into three numbers 16

F or partitions of size two, we need one loop For partitions of size three, we need two nested loops For partitions of size four, we would need three nested loops It gets ugly quickly! And anyway, we need a general method Partitions of n into k numbers 17

Recursion provides an elegant solution The key observation is very simple If p 1 + p 2 + … + p k = n (i.e. p 1 + p 2 + … + p k is a partition of n) Then p 2 + … + p k = n – p 1 (i.e. p 2 + … + p k is a partition of n – p 1 ) Partitions of n into k numbers 18

For example, consider the three partitions of 4 that start with This simple observation is the foundation of a recursive algorithm To partition n: Set p 1 = 1 and find all partitions of n – 1 Set p 1 = 2 and find all partitions of n – 2 (with smallest number 2) Set p 1 = 3 and find all partitions of n – 3 (with smallest number 3) Etc. Partitioning recursively 19 These are the partitions of 3

// list all ways of partitioning n into numbers, given num numbers on ns private static void listParts(int[] ns, int num, int n) { if (n == 0) { for (int i = 0; i < num - 1; i++) System.out.print(ns[i] + " + "); System.out.println(ns[num - 1]); } else { int min = num == 0 ? 1 : ns[num - 1]; for (int p = min; p <= n; p++) { ns[num] = p; listParts(ns, num + 1, n - p); } Partitioning recursively in Java 20

// list all ways of partitioning n into numbers, given num numbers on ns private static void listParts(int[] ns, int num, int n) { if (n == 0) { for (int i = 0; i < num - 1; i++) System.out.print(ns[i] + " + "); System.out.println(ns[num - 1]); } else { int min = num == 0 ? 1 : ns[num - 1]; for (int p = min; p <= n; p++) { ns[num] = p; listParts(ns, num + 1, n - p); } Code dissection 21 Parts assigned so far The number of parts assigned so far The remaining number

// list all ways of partitioning n into numbers, given num numbers on ns private static void listParts(int[] ns, int num, int n) { if (n == 0) { for (int i = 0; i < num - 1; i++) System.out.print(ns[i] + " + "); System.out.println(ns[num - 1]); } else { int min = num == 0 ? 1 : ns[num - 1]; for (int p = min; p <= n; p++) { ns[num] = p; listParts(ns, num + 1, n - p); } Code dissection 22 The base case prints out a complete partition

// list all ways of partitioning n into numbers, given num numbers on ns private static void listParts(int[] ns, int num, int n) { if (n == 0) { for (int i = 0; i < num - 1; i++) System.out.print(ns[i] + " + "); System.out.println(ns[num - 1]); } else { int min = num == 0 ? 1 : ns[num - 1]; for (int p = min; p <= n; p++) { ns[num] = p; listParts(ns, num + 1, n - p); } Code dissection 23 The recursive case first determines the smallest usable number

This ternary operator has the general form x = ? : It is exactly equivalent to if ( ) x = ; else x = ; The ? operator 24

// list all ways of partitioning n into numbers, given num numbers on ns private static void listParts(int[] ns, int num, int n) { if (n == 0) { for (int i = 0; i < num - 1; i++) System.out.print(ns[i] + " + "); System.out.println(ns[num - 1]); } else { int min = num == 0 ? 1 : ns[num - 1]; for (int p = min; p <= n; p++) { ns[num] = p; listParts(ns, num + 1, n - p); } Code dissection 25 The loop tries each usable number in turn

// list all ways of partitioning n into numbers public static void listPartitions(int n) { listParts(new int[n], 0, n); } The first argument is made big enough to store the largest possible partition The second argument says there are no numbers initially The initial call 26

Tracing an example 27 listPartitions(4) listParts({0,0,0,0},0,4) listParts({1,0,0,0},1,3) listParts({1,1,0,0},2,2) listParts({1,1,1,0},3,1) listParts({1,1,1,1},4,0) -> output listParts({1,1,2,0},3,0) -> output listParts({1,2,0,0},2,1) listParts({1,3,0,0},2,0} -> output listParts({2,0,0,0},1,2) listParts({2,2,0,0},2,0) -> output listParts({3,0,0,0},1,1) listParts({4,0,0,0},1,0) -> output 4 Four options from 1 Three options from 1 One option from 2 Two options from 1

Partitions of 10 28