Download CS 180 Problem Solving and OO Programming Fall 2010

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Java ConcurrentMap wikipedia , lookup

Lattice model (finance) wikipedia , lookup

Quadtree wikipedia , lookup

B-tree wikipedia , lookup

Interval tree wikipedia , lookup

Binary search tree wikipedia , lookup

Transcript
CS 180 Problem Solving and Object Oriented
Programming
Fall 2011
http://www.cs.purdue.edu/homes/apm/courses/CS180Fall2011/
This Week:
Notes for Week 15:
Nov 28-Dec 2, 2011
Aditya Mathur
Department of Computer Science
Purdue University
West Lafayette, IN, USA
11/28-30 1.
2.
3.
Exceptions
Recursion
Dynamic data structures
Readings and Exercises for Week 15
Readings:
Chapter: 8.4, 12.1, 12.2, 12.3; 18.1, 18.8
Exercises:
8.6, 12.2, 12.3, 18.1, 18.10
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
2
Announcements
•
Project 5 due on Tuesday Dec 6, 11:59pm. Implement
incrementally.
•
Please DO attend the class on Monday Dec 5.
•
Programming competition. Chief Guest Dr. Tim Korb.
•
Details of Final Exam on Wednesday Dec 7.
•
Please complete course evaluation. Thanks.
•
Special class. Sunday Dec 11, 2011. 4pm. LWSN 3102AB
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
3
Exam 2 Statistics
Average: 75.8
Median: 83
Std Dev: 21.44
A+: 100/98
A: 97/94
A-: 93/90
B+: 89/87
B: 86/82
B-: 81/78
C+: 77/73
C: 72/67
C-: 66/56
D: 55/40
F: 39/0
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
4
Exceptions
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
5
Exceptions
An abnormal or unexpected condition during execution.
When such a condition occurs, Java run time
system does not always know how best to proceed
and hence raises an exception.
Some exceptions must be explicitly handled by the
programmer.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
6
Exception: Example 1
public class ExceptionExampleDiv0{
public static void main(String [] args){
int y=1, z=0;
int x=y/z;
}
}
java.lang.ArithmeticException: / by zero
at ExceptionExampleDiv0.main(ExceptionExampleDiv0.java:8)
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
7
Exception: Example 2
public class ExceptionExampleDiv0{
public static void main(String [] args){
int y=1, z=0;
try{
int x=y/z;
Try-catch not required
}catch(ArithmeticException e){
System.out.println(“Divide by zero:”+e); }
}
Divide by zero java.lang.ArithmeticException: / by zero
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
8
Exception: Unchecked (or Error)
• Arise during runtime due to some programming error.
• Not flagged by the compiler. Programmer may choose to
handle these.
• Not subject to Catch requirement.
Examples:
ArithmeticException
ArrayIndexOutOfBounds
NullPointerException
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
9
Exception: Example 3
public class ExceptionExampleFile{
public static void main(String [] args){
File f=new File("test.txt");
Scanner source=new Scanner(f);
}
}
1 error found:
File:
/Users/apm/www/courses/CS180Fall2010/Notes/Programs/Exc
eptions/ExceptionExampleFile.java [line: 8]
Error:
©Aditya Mathur. CS 180. Fall 2011. Week
/Users/apm/www/courses/CS180Fall2010/Notes/Programs/Exc
11/28/2011
10
15
Exception: Example 4
public class ExceptionExampleFile{
public static void main(String [] args){
File f=new File("test.txt");
try{
Scanner source=new Scanner(f);
}catch(FileNotFoundException e){
System.out.println("File not found "+e);
}
}
}
11/28/2011
File not found java.io.FileNotFoundException: test.txt (No
such file or directory)
©Aditya Mathur. CS 180. Fall 2011. Week
15
11
Exception: Checked exceptions
These are subject to the catch requirement.
Programmer is expected to write code to recover from
these exceptions.
Example:
FileNotFoundException
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
12
Exception: try-catch
try{
code where exception might occur;
try-block
}catch(exception object){
code to handle exception
catch-block
}
A catch-block serves as an exception handler.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
13
Exception: try-catch: multiple catch blocks
try{
code where exception might occur;
try-block
}catch(exception object){
code to handle exception;
catch-block
}catch(another exception object){
code to handle exception;
}
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
Another catchblock
14
Exception: try-catch-finally
try{
Code where exception might occur;
try-block
}catch(exception object){
code to handle exception;
catch-block
}finally{
code to handle exception;
finally-block
}
finally-block always executes after the try-catch blocks
(unless the program exits prior to the control arriving at
the finally block).
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
15
Exception: Not handled
public ExceptionTest(){
Scanner s=new Scanner(new File (“DoesNotExist”));
}
Error:
/Users/apm/www/courses/CS180Fall2011/Notes/Programs/Recur
sion/Tree/ExceptionTest.java:7: unreported exception
java.io.FileNotFoundException; must be caught or declared to be
thrown
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
16
Exception: Throwing
public ExceptionTest() throws Exception{
Scanner s=new Scanner(new File (“DoesNotExist”));
}
A method…NOT a class…can throw an Exception.
This will compile…. BUT…
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
17
Exception: Throwing but not handling later
public ExceptionTest() throws Exception{
Scanner s=new Scanner(new File (“DoesNotExist”);
}
public static void main(String [] arg){
new ExceptionTest();
}
Error:
/Users/apm/www/courses/CS180Fall2011/Notes/Programs/Recur
sion/Tree/ExceptionTest.java:11: unreported exception
java.lang.Exception; must be caught or declared to be thrown…
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
18
Exception: Throwing but handling later
public ExceptionTest() throws Exception{
Scanner s=new Scanner(new File (“DoesNotExist”);
}
public static void main(String [] arg){
try{
new ExceptionTest();
}catch(Exception e){
}
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
19
Recursion
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
20
What is recursion?
Recursion is a technique to code functions (or methods) in Java.
We say that a method is recursive, when it calls itself. This
is known as direct recursion.
Indirect recursion occurs when a method is called, before it
completes, by another method.
Recursion is complementary to iteration. While solving a
problem, you may choose to use either.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
21
Example: Factorial
Definition: Iterative [n>=0]
!n= 1, if n=0 or 1
= 1*2*3*…*n;
Definition: Recursive [n>=0]
!n= 1, if n=0 or 1
= n*!(n-1), if n>1
11/28/2011
Basis
Recursion
©Aditya Mathur. CS 180. Fall 2011. Week
15
22
Example: Factorial: Iterative method
Definition: Iterative [n>=0]
!n= 1,
if n=0 or 1
= 1*2*3*…*n; otherwise
public int factIter(int n){
if(n==0 || n==1)
return 1;
int prod=1;
for (int i=2; i<=n; i++){
prod=prod*i;
}
return (prod);
}
!5=prod=1*2*3*4*5
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
23
Example: Factorial: Recursive method
Definition: Recursive [n>=0]
!n= 1, if n=0 or 1
= n*!(n-1), if n>1
public int factRecur(int n){
if(n==0 || n==1){
return 1;
}else{
return (n*factRecur(n-1));
}
}
factRecur(5)=5*factRecur(4)*factRecur(3)*factRecur(2)*factRecur(1)
=5*factRecur(4)*factRecur(3)*factRecur(2)*1
=5*factRecur(4)*factRecur(3)*2*1
=5*factRecur(4)*3*2*1
=5*4*3*2*1 ©Aditya Mathur. CS 180. Fall 2011. Week
11/28/2011
24
15
Recursion versus Iteration
Iteration suffices for most problems that arise in
practice.
However, in some cases recursion allows compact and
quick solution. An example follows.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
25
Announcements
•
Feast with faculty today at 6:30pm Ford Dining Hall. All
are welcome.
•
Project 4 grades are on Blackboard. If your submitted
program was working but you received a low grade
then please contact TA Julian Stephen.
•
11/28/2011
Programming competition: Round 2: Saturday 6pm.
LWSN 3102. Three teams will be selected for the final
round.
©Aditya Mathur. CS 180. Fall 2011. Week
15
26
Towers of Hanoi: The problem
Given: Three towers A, B, and C. A contains n discs arranged
from bottom to top as shown below.
Problem: Find a sequence of moves such that at the end of
these moves all discs are in C. No larger disc should ever be on
top of a smaller disk. Only one disk can be moved at a time
from one tower to another. Only the top disc can be moved
from a tower.
A
11/28/2011
B
©Aditya Mathur. CS 180. Fall 2011. Week
15
C
27
Towers of Hanoi: Initial and final configurations
Initial configuration
A
B
C
A
B
C
Final configuration
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
28
Towers of Hanoi: Iterative solution
Try this! This will be difficult but certainly worth a try.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
29
Towers of Hanoi: Recursive solution
What is a move?
Only one disc can be moved from one tower to
another. Hence we will write a move as:
moveADisc (TA, TB);
TA is the tower from where the top disc is
moved
and placed on top in tower TB.
move (TA, TB, TC, n);
This will move n discs from tower TA to tower TB
via tower TC while ensuring the constraints.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
30
Towers of Hanoi: Recursive solution: Visualization
Start
1
3
A
B
C
2
A
B
C
A
B
C
4
A
11/28/2011
B
C
©Aditya Mathur. CS 180. Fall 2011. Week
15
31
Towers of Hanoi: Recursive program: Live
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
32
Towers of Hanoi: Challenge!
How many moves are required to move n discs from
tower A to tower C?
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
33
Recursion and Dynamic data structures
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
34
Dynamic data structures
Static data structure: Array
Useful when size of the data structure is not known in advance.
Useful for designing efficient algorithms.
Examples: Stack, Linked list, binary tree, etc.
In Java: ArrayList, Vector
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
35
Tree (Binary)
Tree with one node (the root)
Left link
Right link
Tree with a root linked to two
other nodes.
Another tree.
Left link
11/28/2011
Right link
©Aditya Mathur. CS 180. Fall 2011. Week
15
36
Tree: with data
25
Tree with one node (the root)
25
Right link
Left link
14
Tree with a root linked to two
other nodes.
39
Another tree.
25
Left link
14
Right link
39
Do you see a pattern?
9
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
37
Tree: Binary search
25
Left link
14
9
11/28/2011
Right link
Does x exist in the tree?
39
boolean find(int x, Node root){
if(x is at the root)
return true;
if (x< value at the root)
return find (x, root.leftLink);
else
return find(x, root.rightLink);
}
©Aditya Mathur. CS 180. Fall 2011. Week
15
38
Binary search tree: Creation
Left and right
links are null.
25
Add 25. Start with an empty
tree and add a node. Set root
to be this node.
25
39
25
Left link
14
11/28/2011
Add 39. This is greater than
the number at the root.
Hence add a new node to the
right subtree.
Add 14. As this is less than
the value at the root, add a
Right link
new node to the left of the
39
root.
Each data item
exists exactly once
©Aditya Mathur. CS 180. Fall 2011. Week
in the tree.
39
15
Tree: Non-empty binary search tree
Has a root
Each node has 0, 1, or 2 links. Links are generally termed
as left and right links.
Each node has a data item in it.
Suppose that node n points to nodes n1 (left) and
n2 (right). Then the data at node n1 is less than
that at n and the data at node n2 is greater than
that at node n.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
40
Binary search tree creation: Exercise
What will a binary search tree look like after the following
numbers are added in this sequence given:
5, 29, -4, 23, 99, 3?
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
41
Live demo: Tree creation and traversal.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
42
Week 15: November 28-Dec 2, 2011
Hope you enjoyed this week!
Questions?
Contact your recitation instructor. Make
full use of our office hours.
11/28/2011
©Aditya Mathur. CS 180. Fall 2011. Week
15
43