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.

Slides:



Advertisements
Similar presentations
CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
Advertisements

CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
1 Various Methods of Populating Arrays Randomly generated integers.
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
Intelligent CS 5 ? HW 11 (1 problem !) M/T sections W/Th sections due Sunday, 11/14 at midnight due Monday, 11/15 at midnight Recitation for HW11 -- Friday.
Homework 14 Due ( MT sections ) ( WTh sections ) at midnight Sun., 12/7 Mon., 12/8 Problems
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Wednesday, 12/11/02, Slide #1 CS 106 Intro to Comp. Sci. 1 Wednesday, 12/11/02  QUESTIONS??  Today: CLOSING CEREMONIES!  HW #5 – Back Monday (12/16)
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
CS1101: Programming Methodology Aaron Tan.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Nelson Series Talk Wed, 11/10 7:00 pm Security, Liberties and Trade-offs in the War on Terrorism Since 9/11, we have enacted the Patriot Act, tighter screening.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Homework 11 Due ( MT sections ) ( WTh sections ) at midnight Sun., 11/14 Mon., 11/15 Problems
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Homework 3 Due ( MT sections ) ( WTh sections ) at midnight Sun., 9/21 Mon., 9/22 Problems
This week in CS 5 HW 9 (2 problems) M/T sections W/Th sections due Sunday, 11/4 at midnight due Monday, 11/5 at midnight Recitation for HW9 -- Friday 11/2.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
Homework 9 Due ( M & T sections ) ( W & Th sections ) at midnight Sun., 11/3 Mon., 11/4 Problems
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.
Recitation 2 James Wei Professor Peck 1/17/2013. Covered in this Recitation Arrays Variable Scoping Local variables Instance variables Class variables.
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 6: Recursion Lecturer: Santokh Singh Assignment 1 due tomorrow. Should have started working.
1 CS161 Introduction to Computer Science Topic #9.
Homework 8 Due ( MT sections ) ( WTh sections ) at midnight Sun., 10/28 Mon., 10/29 Problems Reading is under week 7, however.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion.
Code Compression the benefits of looping... Today in CS 5 HW 4 - (3 problems) M/T sections W/Th sections due Sunday, 9/26 at midnight due Monday, 9/27.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
The last CS 5 lecture you’ll ever need! Inducing labor for the machine! == Reducing labor for humans! On Warner Brothers' insistence, we affirm that this.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office Functional Programming.
Recursion in Java The answer to life’s greatest mysteries are on the last slide.
RECURSIONL27-L28. To learn and the following concepts To design a recursive algorithm To solve problems using recursion To understand the relationship.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CS 121 – Intro to Programming:Java - Lecture 4 Announcements Course home page: Owl due soon; another.
Midterm 2 Review Notes on the CS 5 midterm Take-home exam due by 5:00 pm Sunday evening (11/14) Hand in your solutions under the door of my office, Olin.
Homework 10 Due ( MT sections ) ( WTh sections ) at midnight Sun., 11/10 Mon., 11/11 Problems
Nelson Series Talk Wed, 10/13 7:00 pm HMC’s Galileo Auditorium On Robots, Probability, and Artificial Intelligence This talk will expose the audience.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
C++ Memory Management – Homework Exercises
Recursion Version 1.0.
Homework 12 Sun., 11/24 Due Mon., 11/25 Problems (2 of them)
CS 326 Programming Languages, Concepts and Implementation
Nelson Speaker Series Monica Lam, Stanford
Recursion Chapter 18.
EECS 110: Lec 4: Functions and Recursion
Recursion Method calling itself (circular definition)
Presentation transcript:

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!

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

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

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] = getMax(s2); } b.removeMove(c); } else s[c] = -1.0; } return s; public double[] plyN(Board b, int N) { } self-reference?

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

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...

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 }

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 }

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

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

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

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...

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?

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

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

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

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!

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); }

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: array initialization

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

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

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

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” Hint Use +

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

“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?

“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] min(A,0,3) should return 4.2

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

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

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

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”

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

Recursion Mantra Let recursion do the work for you.

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

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 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

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

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); }

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

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]

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

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

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”;

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...

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

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

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