Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 5 HW 12 (2 problems) M/T sections W/Th sections due Sunday, 11/21 at midnight due Monday, 11/22 at midnight Recitation for HW12 -- Friday 8:00am Looking.

Similar presentations


Presentation on theme: "CS 5 HW 12 (2 problems) M/T sections W/Th sections due Sunday, 11/21 at midnight due Monday, 11/22 at midnight Recitation for HW12 -- Friday 8:00am Looking."— Presentation transcript:

1

2 CS 5 HW 12 (2 problems) M/T sections W/Th sections due Sunday, 11/21 at midnight due Monday, 11/22 at midnight Recitation for HW12 -- Friday 8:00am Looking back / Looking ahead Reading: weeks 12/13: Recursion Week 12 (this week): Week 14: Week 15: Recursion Software engineering + algorithms Is there science in CS ? NO CS 5 next week… Final 2 Labs: up to you ACM results… C SKILLS 5? C SCIENCE 5!

3 public static double factorial(int N) { if (N < 2) { return 1.0; } else { return N * factorial(N-1); } Recursion: factorial example Base Case Recursive Step

4 Natural scenes seascapes mountain terrain the 2d algorithm...

5 N Ply double[] s = new double[7]; for (int c=0 ; c<7 ; ++c) { if (b.allowsMove(c)) { b.addMove(c,me()); if (b.isOver()) s[c] = evaluate(b); else { Player foe = new Player(you(),N-1,2); double[] s2 = foe.findScores(b); s[c] = 100 - getMax(s2); } b.removeMove(c); } else s[c] = -1.0; } return s; public double[] plyN(Board b, int N) { } self-reference?

6 Problem 2 / Final Project A “film database” application: 5 classes class name data member data member type ??

7 Hw 12 Problem 2 -- Two tasks Implement the main menu (in the CS5App class) Please choose an action from the following list: 0 Display All Directors 1 Display All Films 2 Display Films by Title 3 Display Films by Director 4 Display Films by Year 5 Display Films by Rating (G, PG, …) 6 Display Films by Review (0 to 10) 7 Add a New Film 8 Save film database to file 9 Load film database from file 42 Quit Create skeleton versions of the necessary classes...

8 Problem 2 - skeleton code + comments Methods Classes Data Members public static void main(String[] args) public static void printMenu() public static void saveDB(String file) public static void readDB(String file) public static void readFilm() CS5App public Film(String title, int year, String rating, double review, Director dir) public String getTitle() public int getYear() public String getRating() public double getReview() public void display() public void save() Film String title int year String rating double review Director dir all private ! static FilmDB F static DirectorDB D // comment here public String getRating() { return }

9 Methods Classes Data Members Director public FilmDB(int capacity) public boolean isFull() public int getCount() public void addFilm(Film f) public boolean checkForFilm(String fulltitle) public void saveAllFilms() public void displayAllFilms() public void displayFilmsByTitle(String titlepiece) public void displayFilmsByYear(int year) public void displayFilmsByRating(String rating) public void displayFilmsByReview(double minreview) FilmDB int count Film[] Films DirectorDB String fname String lname FilmDB filmDB similar to FilmDB below – see the assignment description… public Director(String fn, String ln, int capacity) public String getFullName() public String getFirstName() public String getLastName() public FilmDB getFilmDB() all private ! // comment here! public FilmDB getFilmDB() { return }

10 static static stuff belongs to a class, not an object H.pl(“I’m a static method”); getMax(double[] s); printMenu(); Math.sqrt(Math.PI + Math.E); If static stuff is in another class, use that class’s name! in the CS5App class in the Player class in the CS5App class static double PI, E; static FilmDB F; in the Player class in the Math class in the Film class char checker; String title; USING STATIC METHODS STATIC DATA NONSTATIC DATA seen globally in all of the class’s methods… data that is different for every object of the class type

11 Self-referential data ? A film database application: class Director class Film String title int year String rating double review Director dir Director dir String fname String lname FilmDB filmDB FilmDB filmDB class FilmDB int count Film[] films Film[] films films[0]films[1] class Director { private String fname; private String lname; private FilmDB filmDB; // method skeletons… class Film { private String title; private int year; … private Director dir; // method skeletons class FilmDB { private int count; private Film[] films; // method skeletons

12 Recursion is defining something in terms of itself 5! = 5 * 4 * 3 * 2 * 1 N! = N * (N-1) * (N-2) * … * 3 * 2 * 1 factorial

13 Recursion -- warning ! public static double factorial(int N) { return N * factorial(N-1); } No base case -- the calls to factorial will never stop! Make sure you have a base case, then worry about the recursive step...

14 public static double factorial(int N) { if (N < 2) { return 1.0; } else { return N * factorial(N-1); } Recursion: factorial example Base Case Recursive Step shorter?

15 public static double factorial(int N) { if (N < 2) return 1.0; else return N * factorial(N-1); } Recursion: factorial example Slightly shorter version without curly braces... Even shorter versions soon! Base Case Recursive Step

16 Recursion -- how it works factorial(5) 5 * factorial(4) 4 * factorial(3) 3 * factorial(2) 2 * factorial(1) 1.0 5 * 4 * 3 * 2 * 1.0 is 120.0

17 Recursion -- why ? Exploits self-similarity Produces short, elegant code Less work ! Skeptical ? use the ? : operator : double factorial(int N) { } thought code the ratio:

18 Recursion Mantra Let recursion do the work for you. I nodded off at the keyboard and when I woke up, my program was done! I could do that in my sleep! Says stunned CS 5 student: Delighted CodeWarrior user plans on more Sunday night naps!

19 Recursion for concise coding public static double exp(double x, int n) { if (n < 0) return 0.0; return power(x,n)/fac(n) + exp(x,n-1); } public static void main(String[] args) { double d = exp(2.0,10); }

20 Recursion with arrays double[] A = { 4, 7, -10, 4, 1 }; sum(A, 0, 4) returns 6.0 sum(A, 3, 4) returns 5.0 Base Case: Recursive Step: 47-1041 0 1 2 34 array initialization

21 Recursion with arrays Recursively summing an array: double sum(double[] A, int L, int U)

22 Recursion -- not just numbers Relationships Self-similarity elsewhere... Natural phenomena Names -- acronyms What is an “ancestor” ? how much stem? GNU

23 A String of recursive methods RJACKSON GATTACA How many A ’s are in a particular string? Base Case: Recursive Step:

24 substring String s = “RECURSION”; s.substring(3, 5) is the string “UR” s.substring(0, 3) is the string is the string “ECURSION” is the string “CURSE” 0 1 2 3 4 5 6 7 8 Hint Use +

25 A String of recursive methods int countAs(String s) returns the number of A ’s in the String s

26 “Quiz” String removeAs(String s) { } returns a string that is the same as s, except without any A ’s boolean isAlph(String s) { } returns true if s is in alphabetical order, false otherwise (ties OK) Names: Extra: what’s a six-letter English word for which isAlph returns true?

27 “Quiz” double min(double[] A, int L, int U) { write recursive code to return the minimum value in the array A between indices L and U (inclusive). page 2 A A[0]A[4]A[1]A[2]A[3] 5.14.27.7421.7 min(A,0,3) should return 4.2

28 Recursion can do anything! String removeAs(String s) boolean isAlph(String s) returns true if s is in alphabetical order, false otherwise (ties OK) returns a string that is the same as s, except without any A ’s removeAs(“GATTACA”) returns “GTTC” isAlph(“BART”) returns false isAlph(“LOOPY”) returns false isAlph(“BERT”) returns true

29 Problem 1 Write recursive methods for double factorial(int N) double power(double b, int N) raises b to the N power double harmonic(int N) adds 1/1 + 1/2 + … + 1/N boolean isPalindrome(String s) true if s is a palindrome; false otherwise String reverse(String s) returns the reversal of s void sort(double[] A, int L, int U) sorts A between index L and U (inclusive) void moveMinToLeft(double[] A, int L, int U) swaps elements so that the smallest element between index L and U is at location L

30 Problem 1 Create a menu that allows a user to call each method: Welcome to the recursive roster! Options: (1) factorial (2) power (3) harmonic series (4) palindrome checker (5) string reverser (6) min mover (7) list sorter (8) longest common subsequence [Extra] (9) quit each of these will be a recursive method in the CS5App class

31 Lab Today Extra credit: a biological application Take advantage of us! Given two strings, what is a longest common subsequence? public static String LCS(String s1, String s2) s1 = “hamburger” s2 = “cheeseburger” s1 = “GATTTCAAGTGAC” s2 = “CTTAGACATAGGT” LCS(s1,s2) returns “hburger” LCS(s1,s2) returns “TTCAAGG”

32 Testing N Ply ‘X’ ‘O’ With a 4-ply lookahead, X will think everything looks equivalent in this case With a 5-ply lookahead, X will know to move to column 3 0 1 2 3 4 5 6

33 Recursion Mantra Let recursion do the work for you.

34 Natural scenes seascapes mountain terrain the 2d algorithm...

35 Recursive Data Can data contain other data of the same type? class Wart { int idNumber; Wart neighbor; } Wart wally Wart int neighbor idNumber

36 wally wally.neighbor wally.neighbor.neighbor wally.neighbor.neighbor.neighbor int idNumber Wart neighbor int idNumber Wart neighbor int idNumber Wart neighbor int idNumber Wart neighbor wally wally.neighbor wally.neighbor.neighbor wally.neighbor.neighbor.neighbor int idNumber Wart neighbor int idNumber Wart neighbor int idNumber Wart neighbor int idNumber Wart neighbor

37 Recursive Data Can data contain other data of the same type? class Wart { int idNumber; Wart neighbor; } Wart wally Wart int neighbor idNumber wally wally.neighbor wally.neighbor.neighbor wally.neighbor.neighbor.neighbor int idNumber Wart neighbor int idNumber Wart neighbor int idNumber Wart neighbor int idNumber Wart neighbor

38 Ridiculously short code! Using the ? : operator... double factorial(int n) { return n<2 ? 1 : n*factorial(n-1); } double sum(double[] arr, int L, int H) { return L>H ? 0.0 : arr[L]+sum(arr,L+1,H); }

39 addMove Class: Board Object: b b.addMove(3,‘X’) ‘X’ ‘O’ changes b by adding checker ‘X’ into row 3 new‘X’ b before b after

40 Self-referential data ? A film database application: class FilmDB class Director class Film String title int year String rating double review Director dir Director dir String fname String lname FilmDB filmDB FilmDB filmDB int count Film[] films Film[] films films[0]films[1]

41 (Non) deterministic recursion Koch snowflake Deterministic recursion Recursion with randomness

42 Recursion can do anything! String removeAs(String s) boolean isAlph(String s) returns true if s is in alphabetical order, false otherwise returns a string that is the same as s, except without any A ’s

43 No base case -- the calls to factorial will never stop! As with mathematical induction, base cases are critical... When writing recursive code Make sure you have a base case ! Check that the base case is correct !! double sum(double[] arr, int L, int H) { return L>H ? 0.0 : arr[L]+sum(arr,L+1,H); } s = “GATTACA”;

44 Computer Science 5 HW 12 (2 problems + E.C.) M/T sections W/Th sections due Sunday, 11/24 at midnight due Monday, 11/25 at midnight Recitation for HW12 -- Friday 8:00am Looking back / Looking ahead Connect Four Results... Reading: Week 12 re: recursion Week 12 (this week): Week 14: Week 15: Recursion Software engineering + algorithms Is there science in CS ? Midterm 2 Results...

45 Recursion -- not just numbers Relationships Self-similarity elsewhere... Natural phenomena Names -- acronyms What is an “ancestor” ? EMACS EINE ZWEI all stem!

46 Extra credit: N-ply search Board Evaluation Depth of Search 1-ply search2-ply search3-ply searchN-ply search evaluate (N-1) - ply... advantage: black advantage: red 1 - ply 2 - ply int chooseMove(Board b, char ox, int ply) chooseMove1PlychooseMove2PlychooseMove3Ply

47 Problem 2 / Final Project class name data member data member type CS5App (for main)


Download ppt "CS 5 HW 12 (2 problems) M/T sections W/Th sections due Sunday, 11/21 at midnight due Monday, 11/22 at midnight Recitation for HW12 -- Friday 8:00am Looking."

Similar presentations


Ads by Google