to a man with a hammer everything looks like a nail mark
play

"To a man with a hammer, everything looks like a nail" - PowerPoint PPT Presentation

Topic 12 Underneath the Hood. Introduction to Recursion "To a man with a hammer, everything looks like a nail" -Mark Twain CS314 Recursion 2 The Program Stack method1 and method2 // in class Mice When you invoke a method in


  1. Topic 12 Underneath the Hood. Introduction to Recursion "To a man with a hammer, everything looks like a nail" -Mark Twain CS314 Recursion 2 The Program Stack method1 and method2 // in class Mice When you invoke a method in your code public static int method1(int a, int b) { what happens when that method is done? int r = 0; if (b != 0) { public class Mice { int x = a / b; public static void main(String[] args) { int y = a % b; int x = 37; r = x + y; int y = 12; } method1(x, y); return r; int z = 73; } int m1 = method1(z, x); public static void method2(int x, int y) { method2(x, x); x++; } y--; int z = method1(y, x); // method1 and method2 System.out.print(z); // on next slide } CS314 Recursion 3 CS314 Recursion 4

  2. Basic CPU Operations The Program Stack A CPU works via a fetch When your program is run on a processor, the command / execute command commands are converted into another set of loop and a program counter instructions and assigned memory locations. Instructions stored in memory (Instructions are data!) normally a great deal of expansion takes place public static void main(String[] args) { int x = 37; // 1 int x = 37; // 1 int y = 12; // 2 int y = 12; // 2 method1(x, y); // 3 method1(x, y); // 3 int z = 73; // 4 int z = 73; // 4 int m1 = method1(z, x); // 5 int m1 = method1(z, x); // 5 method2(x, x); // 6 method2(x, x); // 6 What if the first instruction of the method1 is } stored at memory location 50? CS314 Recursion 5 6 Clicker 1 - The Program Stack // in class Mice int x = 37; // 1 public static int method1(int a, int b) { int y = 12; // 2 int r = 0; // 51 method1(x, y); // 3 if (b != 0) { // 52 int x = a / b; // 53 int z = 73; // 4 int y = a % b; // 54 int m1 = method1(z, x); // 5 r = x + y; // 55 method2(x, x); // 6 } return r; // 56 Instruction 3 is really saying jump to instruction } 50 with parameters x and y public static void method2(int x, int y) { In general what happens when method1 finishes? x++; // 60 y--; // 61 A. program ends B. goes to instruction 4 int z = method1(y, x); // 62 System.out.print(z); // 63 C. goes back to whatever method called it } CS314 Recursion 7 8 CS314 Recursion

  3. Activation Records and the The Program Stack Program Stack Data may either be When a method is invoked all the relevant added ( pushed) or information about the current method removed (popped) from top (variables, values of variables, next line of a stack but it is always code to be executed) is placed in an from the top. activation record A stack of dishes The activation record is pushed onto the which dish do we have program stack easy access to? A stack is a data structure with a single access point, the top. CS314 Recursion 9 CS314 Recursion 10 A Problem Write a method that determines how much space is take up by the files in a directory A directory can contain files and directories Using Recursion How many directories does our code have to examine? How would you add up the space taken up by the files in a single directory Hint: don't worry about any sub directories at first CS314 Recursion 12

  4. Clicker 2 Sample Directory Structure How many levels of directories have to be visited? scottm A. 0 AP cs307 B. 1 C. 8 m2.txt m1.txt A.pdf D. Infinite AB.pdf hw E. Unknown a1.htm a2.htm a3.htm a4.htm CS314 Recursion 13 CS314 Recursion 14 Java File Class Code for getDirectorySpace() File (String pathname) Creates a new // pre: dir is a directory and dir != null public static long spaceUsed(File dir) { File instance by converting the given if( dir == null || !dir.isDirectory()) pathname. throw new IllegalArgumentException(); long spaceUsed = 0; boolean isDirectory() Tests whether File[] subFilesAndDirs = dir.listFiles(); the file denoted by this abstract pathname is if(subFilesAndDirs != null) a directory. for(File sub : subFilesAndDirs) if(sub != null) File[] listFiles() Returns an array if(!sub.isDirectory()) // sub is a plain old file of abstract pathnames denoting the files in spaceUsed += sub.length(); else // else sub is a directory the directory denoted by this abstract spaceUsed += spaceUsed(sub); pathname. return spaceUsed; } CS314 Recursion 15 CS314 Recursion 16

  5. Clicker 3 Iterative getDirectorySpace() public int getDirectorySpace(File d) { Is it possible to write a non recursive method ArrayList<File> dirs = new ArrayList<>(); dirs.add(d); to determine space taken up by files in a int total = 0; directory, including its subdirectories, and while( dirs.size() > 0 ) { File temp = dirs.remove(dirs.size() 1); their subdirectories, and their subdirectories, File[] filesAndSubs = temp.listFiles(); if (filesAndSubs != null) { and so forth? for (File f : filesAndSubs) { if (f != null) { A. No if (f.isFile()) total += f.length(); B. Yes else dirs.add(f); C. It Depnds } } } return total; } CS314 Recursion 17 CS314 Recursion 18 The 3 plus 1 rules of Recursion 1. Know when to stop 2. Decide how to take one step 3. Break the journey down into that step and a Wisdom for Writing Recursive smaller journey Methods 4. Have faith From Common Lisp: A Gentle Introduction to Symbolic Computation by David Touretzky CS314 Recursion 20

  6. Writing Recursive Methods N! Rules of Recursion the classic first recursion problem / example 1. Base Case: Always have at least one case that N! can be solved without using recursion 5! = 5 * 4 * 3 * 2 * 1 = 120 2. Make Progress: Any recursive call must int res = 1; progress toward a base case. for(int i = 2; i <= n; i++) 3. "You gotta believe." Always assume that the res *= i; recursive call works. (Of course you will have to design it and test it to see if it works or prove that it always works.) A recursive solution solves a small part of the problem and leaves the rest of the problem in the same form as the original CS314 Recursion 21 CS314 Recursion 22 Tracing Fact With the Factorial Recursively Program Stack Mathematical Definition of Factorial 0! = 1 System.out.println( fact(4) ); N! = N * (N - 1)! The definition is recursive. // pre n >= 0 public int fact(int n) { if(n == 0) return 1; else return n * fact(n-1); } top System.out.println( fact(4) ); CS314 Recursion 23 CS314 Recursion 24

  7. Calling fact with 4 Calling fact with 3 3 in method fact n partial result = n * fact(n-1) 4 in method fact 4 in method fact n n top partial result = n * fact(n-1) partial result = n * fact(n-1) top System.out.println( fact(4) ); System.out.println( fact(4) ); CS314 Recursion 25 CS314 Recursion 26 Calling fact with 2 Calling fact with 1 1 in method fact n partial result = n * fact(n-1) 2 2 in method fact in method fact n n top partial result = n * fact(n-1) partial result = n * fact(n-1) 3 3 in method fact in method fact n n top partial result = n * fact(n-1) partial result = n * fact(n-1) 4 4 in method fact in method fact n n partial result = n * fact(n-1) partial result = n * fact(n-1) System.out.println( fact(4) ); System.out.println( fact(4) ); CS314 Recursion 27 CS314 Recursion 28

  8. Calling fact with 0 and returning 1 Returning 1 from fact(1) 0 in method fact n n 1 in method fact returning 1 to whatever method called me partial result = n * 1, 1 in method fact n top return 1 to whatever method called me partial result = n * fact(n-1) 2 in method fact top n 2 in method fact n partial result = n * fact(n-1) partial result = n * fact(n-1) 3 in method fact n 3 in method fact n partial result = n * fact(n-1) partial result = n * fact(n-1) 4 in method fact n 4 in method fact n partial result = n * fact(n-1) partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion System.out.println( fact(4) ); 29 CS314 Recursion 30 Returning 2 from fact(2) Returning 6 from fact(3) 2 in method fact n partial result = 2 * 1, return 2 to whatever method called me 3 in method fact n 3 in method fact n top partial result = 3 * 2, partial result = n * fact(n-1) return 6 to whatever method called me 4 4 in method fact in method fact n n top partial result = n * fact(n-1) partial result = n * fact(n-1) System.out.println( fact(4) ); System.out.println( fact(4) ); CS314 Recursion 31 CS314 Recursion 32

  9. Returning 24 from fact(4) Calling System.out.println 4 in method fact n System.out.println( 24 ); partial result = 4 * 6, return 24 to whatever method called me top ?? top System.out.println( fact(4) ); CS314 Recursion 33 CS314 Recursion 34 Evaluating Recursive Methods you must be able to evaluate recursive methods public static int mystery (int n){ Evaluating Recursive Methods if( n == 0 ) return 1; else return 3 * mystery(n-1); } // what is returned by mystery(3) CS314 Recursion 36

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend