Programming Abstractions

Slides:



Advertisements
Similar presentations
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Advertisements

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.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
1 Chapter 18-1 Recursion Dale/Weems. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
Stacks CISC181 Spring 2004 P. T. Conrad University of Delaware.
CS 106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
© 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.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Sequential & Object oriented Programming
1 Joe Meehean.  call themselves directly  or indirectly void f(){... f();... } void g(){... h();... } void h(){... g();... }
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Programming Abstractions Cynthia Lee CS106X. Today’s Topics ADTs  Map › Example: counting words in text  Containers within containers › Example: reference.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
CS 106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH 2, APPENDIX E.
Programming Abstractions Cynthia Lee CS106X. Topics:  Finish up heap data structure implementation › Enqueue (“bubble up”) › Dequeue (“trickle down”)
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Programming Abstractions Cynthia Lee CS106B. Today’s Topics ADTs  Map › Example: counting words in text  Containers within containers › Example: reference.
Function Recursion to understand recursion you must understand recursion.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 Data Structures CSCI 132, Spring 2016 Notes_ 5 Stacks.
Programming Abstractions Cynthia Lee CS106X. Recursion! The exclamation point isn’t there only because this is so exciting, it also relates to one of.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion Powerful Tool
Programming Abstractions
Chapter Topics Chapter 16 discusses the following main topics:
Programming Abstractions
to understand recursion you must understand recursion
CS 106X – Programming Abstractions in C++
Programming Abstractions
Programming Abstractions
Programming Abstractions
Programming Abstractions
Recursion Chapter 12.
Programming Abstractions
Programming Abstractions
Programming Abstractions
COMPSCI 107 Computer Science Fundamentals
Programming Abstractions
to understand recursion you must understand recursion
Announcements Final Exam on August 17th Wednesday at 16:00.
Programming Abstractions
Recursion Output Input
Programming Abstractions
Programming Abstractions
Programming Abstractions
Recursion Data Structures.
Recursion.
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Programming Abstractions
Programming Abstractions
Module 1-10: Recursion.
Chapter 17 Recursion.
Yan Shi CS/SE 2630 Lecture Notes
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Main() { int fact; fact = Factorial(4); } main fact.
Self-Referencing Functions
Standard C++ Library Part II.
Recursive Function Prepared by Harprith ICT2102 Introduction to Data Structure.
Presentation transcript:

Programming Abstractions CS106B Cynthia Lee

Today’s Topics ADTs Containers within containers Example: anagram finder Recursion First steps in this fun/crazy new concept Factorial!

Compound Containers It’s turtles all the way down…

Comparing two similar codes: Vector<int> numbers; numbers.add(1); numbers.add(2); numbers.add(3); Map<string, Vector<int>> mymap; mymap["123"] = numbers; mymap["123"].add(4); cout << "New size: " << mymap["123"].size() << endl; Code option #1 Code option #2 Vector<int> test = mymap["123"]; test.add(4); Predict the outcome: (A) Both print 3 (B) Both print 4 (C) One prints 3, other prints 4 (D) Something else or error

C++ bonus details: This works by returning a reference (!) C++ allows you to define a return type to be a reference In the case of map, this returns a reference to the value at map[key]: ValueType & operator[](const KeyType & key);

Stanford library Map (selected member functions) template <typename KeyType, typename ValueType> class Map { public: void add(const KeyType& key, const ValueType& value); bool containsKey(const KeyType& key) const; ValueType get(const KeyType& key) const; ValueType operator [](const KeyType& key) const; ValueType& operator [](const KeyType& key); ... private: } Redacted… until the second half of the quarter!

Anagram Finder An application of compound Map

“Abstractions” Bacon artists Cab stain rots Crab in toasts Bonsai tracts … http://www.wordsmith.org/anagram/

What would be a good design for this problem? Concept: Unlike the website, we will only show anagrams that are 1 word ↔ 1 word (“moored” ↔ “roomed”, not “abstractions” ↔ “bacon artists”) Have a string that is a “representative” of a group of words that are anagrams of each other Have that string map to a list of those words Map<string, Vector<string>> anagrams; Key trick idea: the representative is the string with the letters sorted (use a function: string sortWord(string word)) moored becomes demoor roomed becomes demoor

What would be a good design for this problem? Concept: Map<string, Vector<string>> anagrams; How would we add a word stored in the string variable word to our collection? anagrams[word] += word; anagrams[word] += sortWord(word); anagrams[sortWord(word)] += word; anagrams[sortWord(word)] += sortWord(word); Other/none/more

What would be a good design for this problem? Concept: Map<string, Vector<string>> anagrams; To add a word to our collection: anagrams[sortWord(word)] += word; To look up a word in our collection to find its anagrams: Vector<string> matches = anagrams[sortWord(query)];

Recursion

Factorial! Recursive mathematical definition n! = if n is 1, then n! = 1 if n > 1, then n! = n * (n – 1)! (0! = 1, but for simplicity we’ll just consider the domain n>0 for today)

Designing a recursive algorithm Recursion is a way of taking a big problem and repeatedly breaking it into smaller and smaller pieces until it is so small that it can be so easily solved that it almost doesn't even need solving. There are two parts of a recursive algorithm: base case: where we identify that the problem is so small that we trivially solve it and return that result recursive case: where we see that the problem is still a bit too big for our taste, so we chop it into smaller bits and call our self (the function we are in now) on the smaller bits to find out the answer to the problem we face

Factorial! Recursive definition n! = Recursive code if n is 1, then n! = 1 if n > 1, then n! = n * (n – 1)! Recursive code long factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); }

Factorial! Recursive definition n! = if n is 1, then n! = 1 if n > 1, then n! = n * (n – 1)! Recursive code: imagining more concrete examples long factorialOf6() { return 6 * factorialOf5(); } long factorialOf5() { return 120;

Factorial! Recursive definition n! = if n is 1, then n! = 1 if n > 1, then n! = n * (n – 1)! Recursive code: imagining more concrete examaples long factorial(int n) { if (n == 1) { return 1; } else { return n * pretendIJustMagicallyKnowFactorialOfThis(n - 1); }

Factorial! Recursive definition n! = Recursive code if n is 1, then n! = 1 if n > 1, then n! = n * (n – 1)! Recursive code long factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); }

Factorial! Recursive code Recursive definition n! = if n is 1, then n! = 1 if n > 1, then n! = n * (n – 1)! long factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); } Pro tip: the recursive “leap of faith” This concept has become part of the mythology of Stanford’s CS106B classes. It speaks to the idea that recursion will start to make sense to you when you just trust that the recursive part works. One way of tricking your brain into summoning this trust is imagining that the recursive call instead calls some different (non-recursive) function that calculates the same thing, like we did at first for factorial().

Digging deeper in the recursion

Factorial! What is the third thing printed when we call factorial(10)? 2 3 7 8 Other/none/more long factorial(int n) { cout << n << endl; //added code if (n == 1) { return 1; } else { return n * factorial(n - 1); }

How does this look in memory? Stack Heap

How does this look in memory? long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 10; long xfac = 0; xfac = factorial(x); main() myfunction() x: xfac: 10 factorial() n: 10 Heap

Memory (A) Memory (B) Memory (C) main() main() main() myfunction() x: xfac: 10 myfunction() x: xfac: 10 myfunction() x: xfac: 10 factorial() n: 10 factorial() n: 9 factorial() n: 10 9 factorial() n: 9 Heap Heap Heap (D) Other/none of the above

The “stack” part of memory is a stack Function call = push Return = pop

The “stack” part of memory is a stack long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; // smaller test case long xfac = 0; xfac = factorial(x); main() myfunction() x: xfac: 4 factorial() n: 4 Heap

The “stack” part of memory is a stack long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); main() myfunction() x: xfac: 4 factorial() n: 4 factorial() n: 3 Heap

The “stack” part of memory is a stack long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); main() myfunction() x: xfac: 4 factorial() n: 4 factorial() n: 3 factorial() n: 2 Heap

The “stack” part of memory is a stack long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); main() myfunction() x: xfac: 4 factorial() n: 4 factorial() n: 3 factorial() n: 2 factorial() n: 1 Heap

Factorial! What is the fourth value ever returned when we call factorial(10)? 4 6 10 24 Other/none/more than one long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); }

The “stack” part of memory is a stack main() long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); myfunction() x: xfac: 4 factorial() n: 4 factorial() n: 3 factorial() n: 2 factorial() n: 1 Return 1 Heap

The “stack” part of memory is a stack main() long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); myfunction() x: xfac: 4 factorial() n: 4 factorial() n: 3 factorial() n: 2 Return 2 Heap

The “stack” part of memory is a stack main() long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); myfunction() x: xfac: 4 factorial() n: 4 factorial() n: 3 Return 6 Heap

The “stack” part of memory is a stack main() long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } void myfunction(){ int x = 4; long xfac = 0; xfac = factorial(x); myfunction() x: xfac: 4 factorial() n: 4 Return 24 Heap

Factorial! Iterative version Recursive version long factorial(int n) { long f = 1; while ( n > 1 ) { f = f * n; n = n – 1; } return f; long factorial(int n) { cout << n << endl; if (n == 1) { return 1; } else { return n * factorial(n - 1); } NOTE: sometimes iterative can be much faster because it doesn’t have to push and pop stack frames. Function calls have overhead in terms of space and time to set up and tear down.