Compsci 100, Fall 2009 5.1 From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.

Slides:



Advertisements
Similar presentations
CSE 373: Data Structures and Algorithms Lecture 5: Math Review/Asymptotic Analysis III 1.
Advertisements

Analysis of Algorithms intro.  What is “goodness”?  How to measure efficiency? ◦ Profiling, Big-Oh  Big-Oh: ◦ Motivation ◦ Informal examples ◦ Informal.
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.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
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.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Analysis of Algorithms Dilemma: you have two (or more) methods to solve problem, how to choose the BEST? One approach: implement each algorithm in C, test.
19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.
SIGCSE Tradeoffs, intuition analysis, understanding big-Oh aka O-notation Owen Astrachan
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
Data Structures and Algorithms Lecture 5 and 6 Instructor: Quratulain Date: 15 th and 18 th September, 2009 Faculty of Computer Science, IBA.
CompSci 100E 10.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Week 2 - Monday.  What did we talk about last time?  Exceptions  Threads  OOP  Interfaces.
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.
Compsci 06/101, Fall Designing Algorithms and Programs l Designing algorithms to be correct and efficient  The most important of these is _______________.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Analysis of Algorithms
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
CPS 100, Spring From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
CompSci 100 Prog Design and Analysis II Sept 16, 2010 Prof. Rodger CompSci 100, Fall
Abstraction IS 101Y/CMSC 101 Computational Thinking and Design Tuesday, September 17, 2013 Marie desJardins University of Maryland, Baltimore County.
Chapter 8 Recursion Modified.
CompSci 100E 12.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Major objective of this course is: Design and analysis of modern algorithms Different variants Accuracy Efficiency Comparing efficiencies Motivation thinking.
CompSci 100e 6.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
CPS 100, Fall From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems.
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
CompSci Analyzing Algorithms  Consider three solutions to SortByFreqs, also code used in Anagram assignment  Sort, then scan looking for changes.
A Computer Science Tapestry 10.1 From practice to theory and back again In theory there is no difference between theory and practice, but not in practice.
CompSci 100E 15.1 What is a Binary Search?  Magic!  Has been used a the basis for “magical” tricks  Find telephone number ( without computer ) in seconds.
CS 150: Analysis of Algorithms. Goals for this Unit Begin a focus on data structures and algorithms Understand the nature of the performance of algorithms.
CPS Today’s topics Programming Recursion Copyrights, patents, and digital media Reading Great Ideas, p Brookshear, Section Online.
CompSci 100e 7.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion Fundamentals of Recursion l Base case (aka exit case)  Simple case that can be solved with no further computation  Does not make a recursive.
Chapter 9 Recursion © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
CPS 100e 5.1 Inheritance and Interfaces l Inheritance models an "is-a" relationship  A dog is a mammal, an ArrayList is a List, a square is a shape, …
CPS Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply.
Recursion in Java The answer to life’s greatest mysteries are on the last slide.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit ä Allows many complex problems.
CSC 143T 1 CSC 143 Highlights of Tables and Hashing [Chapter 11 p (Tables)] [Chapter 12 p (Hashing)]
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
AP National Conference, AP CS A and AB: New/Experienced A Tall Order? Mark Stehlik
Recursion Topic 5.
Analysis: Algorithms and Data Structures
Plan for the Week Review for Midterm Source code provided
Solving Problems Recursively
Decrease-and-Conquer Approach
Compsci 201 Priority Queues & Autocomplete
Compsci 201 Recursion+Percolation
Java Software Structures: John Lewis & Joseph Chase
Announcements Final Exam on August 17th Wednesday at 16:00.
Algorithm design and Analysis
Announcements Final Exam on August 19th Saturday at 16:00.
Announcements Final Exam on December 25th Monday at 16:00.
How to use hash tables to solve olympiad problems
Announcements HW3 grades will be announced this week
Solving Problems Recursively
Solving Problems Recursively
Presentation transcript:

Compsci 100, Fall From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks. Or … l What is recursive DNS?  What IP is fxyztl.com? l What is a linked list?  Where is it used?

Compsci 100, Fall Quota Exceeded: coping with storage l You’re running out of disk space  Buy more  Compress files  Delete files l How do you find your “big” files?  What’s big?  How do you do this?

Compsci 100, Fall BlobCount or edge detection or … l How do we find images? Components? Paths?  Create information from data

Compsci 100, Fall Tools: Solving Computational Problems l Algorithmic techniques and paradigms  Brute-force/exhaustive, greedy algorithms, dynamic programming, divide-and-conquer, …  Transcend a particular language  Designing algorithms, may change when turned into code l Programming techniques and paradigms  Recursion, memo-izing, compute-once/lookup, tables, …  Transcend a particular language  Help in making code work Cope with correctness and maintenance Cope with performance problems

Compsci 100, Fall Tools: Solving Computational Problems l Java techniques  java.util.*, Comparator, Priority Queue, Map, Set, …  These aren’t really Java-specific, but realized in Java  Map, Comparator, Set: C++, Python, ….  We learn idioms in a language and talk about abstractions l Analysis of algorithms and code  Mathematical analysis, empirical analysis  We need a language and techniques for discussion  Theory and practice, real problems and in-the-limit issues l “In theory there is no difference between theory and practice, but in practice there is.” (attributed to many)

Compsci 100, Fall Recursive structure matches code public static long THRESHOLD = L; // one million bytes public static void findBig(File dir, String tab) { File[] dirContents = dir.listFiles(); System.out.println(tab+"**:"+dir.getPath()); for(File f : dirContents){ if (f.isDirectory()) { findBig(f,tab+"\t"); } else { if (f.length() > THRESHOLD){ System.out.printf("%s%s%8d\n",tab,f.getName(), f.length()); } Does findBig call itself?

Compsci 100, Fall Solving Problems Recursively l Recursion: indispensable in programmer’s toolkit  Allows many complex problems to be solved simply  Elegance and understanding in code often leads to better programs: easier to modify, extend, verify (and sometimes more efficient!!)  Sometimes recursion isn’t appropriate, when it’s bad it can be very bad---every tool requires knowledge and experience in how to use it l The basic idea is to get help solving a problem from coworkers (clones) who work and act like you do  Ask clone to solve a simpler but similar problem  Use clone’s result to put together your answer l Need both: call on the clone and use the result

Compsci 100, Fall Print words read, but print backwards l Could store words and print in reverse order, but …  Probably the best approach, recursion works too public void printReversed(Scanner s){ if (s.hasNext()){ // reading succeeded? String word = s.next(); // store word printReversed(s); // print rest System.out.println(word); // print the word } The function printReversed reads a word, only prints word after the clones finish printing  Each clone has own version of the code, own word variable  Who keeps track of the clones?  How many words are created when reading N words? Can we do better?

Compsci 100, Fall Exponentiation l Computing x n means multiplying n numbers  Does it require n multiplies?  What’s the simplest value of n when computing x n ?  If you want to multiply only once, what can you ask a clone? public static double power(double x, int n){ if (n == 0){ return 1.0; } return x * power(x, n-1); } l Number of multiplications?  Note base case: no recursion, no clones  Note recursive call: moves toward base case (unless …)

Compsci 100, Fall Faster exponentiation l Recursive calls made to compute ?  How many multiplies on each call? Is this better? public static double power(double x, int n){ if (n == 0) return 1.0; double semi = power(x, n/2); if (n % 2 == 0) return semi*semi; return x * semi * semi; } l What about an iterative version of this function?  Why might we want such a version?

Compsci 100, Fall Back to Recursion l Recursive functions have two key attributes  There is a base case, aka exit case : no recursion! See print reversed, exponentiation  All other cases make a recursive call, with some measure (e.g., parameter value) that decreases towards the base case Ensure that sequence of calls eventually reaches the base case “Measure” can be tricky, but usually it’s straightforward l Example: finding large files in a directory (on a hard disk)  Why is this inherently recursive?  How is this different from exponentation?

Compsci 100, Fall Thinking recursively: recursive Max public static double recMax(double[] a, int index){ if (index == a.length-1){ // last element, done return a[index]; } double maxAfter = recMax(a,index+1); return Math.max(a[index],maxAfter); } l What is base case (conceptually)?  Do we need variable maxAfter ? Use recMax to implement arrayMax as follows:  Introduce auxiliary variable from arrayMax(a) to …  return recMax(a,0); Recursive methods sometimes use extra parameters; helper methods set this up

Compsci 100, Fall Recognizing recursion: public void change(String[] a, int first, int last){ if (first < last) { String temp = a[first]; // swap first/last a[first] = a[last]; a[last] = temp; change(a, first+1, last-1); } // original call (why?): change(a, 0, a.length-1); l What is base case? (no recursive calls) l What happens before recursive call made? l How is recursive call closer to the base case? Recursive methods sometimes use extra parameters; helper methods set this up

Compsci 100, Fall More recursion recognition public static int value(int[] a, int index){ if (index < a.length) { return a[index] + value(a,index+1); } return 0; } // original call: int v = value(a,0); l What is base case, what value is returned? l How is progress towards base case realized? l How is recursive value used to return a value? l What if a is array of doubles, does anything change? Recursive methods sometimes use extra parameters; helper methods set this up

Compsci 100, Fall From programming techniques to Java l Is recursion a language independent concept?  Do all languages support recursion?  What are the issues in terms of computer/compiler/runtime support? l We use a language and its libraries, study them?  Should we know how to implement ArrayList What are the building blocks, what are our tools  Should we know how to implement different sorts Should we know how to call existing sorts

Compsci 100, Fall Fran Allen l IBM Fellow, Turing Award  Optimizing compilers l Taught high school for two years, then Master’s degree and IBM  Teachers excited me to learn I’ve always felt that theory without practice is maybe nice and maybe pretty, but it’s not going to influence computing as much as the practice side. But the practice has to be backed up with the ability to talk about it, reason about it, and formulate it so that it can be reproduced.

Compsci 100, Fall Blob Counting, Flood Fill l Flood a region with color  Erase region, make transparent,..  How do find the region? l Finding regions, blobs, edges,..  See blob counting code  What is a blob? l Recursion helps, but necessary?  Performance, clarity, …  Ease of development

Compsci 100, Fall Analyzing Algorithms l Consider two solutions to SortByFreqs  Sort, then scan looking for changes  Insert into Set, then count each unique string  Use a Map (TreeMap or HashMap) l What about iterative flood fill?  Is it faster in theory? In practice? l We want to discuss trade-offs of these solutions  Ease to develop, debug, verify  Runtime efficiency  Vocabulary for discussion

Compsci 100, Fall More on O-notation, big-Oh l Big-Oh hides/obscures some empirical analysis, but is good for general description of algorithm  Allows us to compare algorithms in the limit 20N hours vs N 2 microseconds: which is better? O-notation is an upper-bound, this means that N is O(N), but it is also O(N 2 ) ; we try to provide tight bounds. Formally:  A function g(N) is O(f(N)) if there exist constants c and n such that g(N) n cf(N) g(N) x = n

Compsci 100, Fall Running 10 6 instructions/sec NO(log N)O(N)O(N log N)O(N 2 ) , , min 100, hr 1,000, day 1,000,000, min18.3 hr318 centuries