CPS 100, Spring 2008 3.1 Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,

Slides:



Advertisements
Similar presentations
Basic Algorithms on Arrays. Learning Objectives Arrays are useful for storing data in a linear structure We learn how to process data stored in an array.
Advertisements

Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
Computer Science II Recursion Professor: Evan Korth New York University.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Lecture 12 Oct 13, 2008 Some simple recursive programs recursive problem solving, connection to induction Some examples involving recursion Announcements.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
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 Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Copyright 2008 by Pearson Education Building Java Programs Subtype Polymorphism; Sorting (an extended programming example)
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
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.
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.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CompSci 100E 10.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
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.
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
Hopefully this lesson will give you an inception of what recursion is.
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.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
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.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
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.
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
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.
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.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
CPS Today’s topics Programming Recursion Copyrights, patents, and digital media Reading Great Ideas, p Brookshear, Section Online.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
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.
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.
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.
Recursion Topic 5.
Recursion DRILL: Please take out your notes on Recursion
Analysis: Algorithms and Data Structures
Plan for the Week Review for Midterm Source code provided
Solving Problems Recursively
Decrease-and-Conquer Approach
Java Software Structures: John Lewis & Joseph Chase
Announcements Final Exam on August 17th Wednesday at 16:00.
Building Java Programs
Algorithm design and Analysis
Writing Methods AP Computer Science A.
Announcements Final Exam on August 19th Saturday at 16:00.
Building Java Programs
Announcements Final Exam on December 25th Monday at 16:00.
Announcements HW3 grades will be announced this week
Solving Problems Recursively
Solving Problems Recursively
Presentation transcript:

CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming, divide-and-conquer, … l Programming techniques  Recursion, memo-izing, compute-once/lookup, tables, … l Java techniques  java.util.*, Comparator, Priority Queue, Map, Set, … l Analysis of algorithms and code  Mathematical analysis, empirical analysis today This week

CPS 100, Spring Quota Exceeded 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?

CPS 100, Spring 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?

CPS 100, Spring Solving Problems Recursively l Recursion is an indispensable tool in a 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 concepts: call on the clone and use the result

CPS 100, Spring Print words read, but print backwards l Can use an ArrayList, store all the words and print in reverse order  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, prints the word only after the clones finish printing in reverse order  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?

CPS 100, Spring Exponentiation l Computing x n means multiplying n numbers (or does it?)  What’s the easiest value of n to compute 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?

CPS 100, Spring Faster exponentiation l How many recursive calls are made to computer ?  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?

CPS 100, Spring Back to Recursion l Recursive functions have two key attributes  There is a base case, sometimes called the exit case, which does not make a recursive call See print reversed, exponentiation  All other cases make a recursive call, with some parameter or other measure that decreases or moves 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?

CPS 100, Spring Thinking recursively l Problem: find the largest element in an array  Iteratively: loop, remember largest seen so far  Recursive: find largest in [1..n), then compare to 0 th element public static double max(double[] a){ double maxSoFar = a[0]; for(int k=1; k < a.length; k++) { maxSoFar = Math.max(maxSoFar,a[k]); } return maxSoFar; }  In a recursive version what is base case, what is measure of problem size that decreases (towards base case)?

CPS 100, Spring 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 ? We can use recMax to implement arrayMax as follows return recMax(a,0); Recursive methods sometimes use extra parameters; helper methods set this up

CPS 100, Spring Recognizing recursion: public static void change(String[] a, int first, int last){ if (first < last) { String temp = a[first]; // swap a[first], a[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

CPS 100, Spring 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

CPS 100, Spring Recursive example: BlobCount l How do we find images? Components? Paths?  Create information from data

CPS 100, Spring 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, do we 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

CPS 100, Spring java.util.Comparator l How does sorting work in general and in Java?  Characteristics of Java library sort methods  What can be sorted?  How do you change how sorting works? l Use APT ClientsList as an example to explore Comparator  Creating new Comparator: nested class, anonymous class  Access issues: final or “persistent” data (why?) l What does it mean to implement Comparable ?  Other Java interfaces: cloneable, serializable, …

CPS 100, Spring Eugene (Gene) Myers l Lead computer scientist/software engineer at Celera Genomics (now at Berkeley,now at …?) l "What really astounds me is the architecture of life. The system is extremely complex. It's like it was designed." … "There's a huge intelligence there."