2/26/20011 cse 121/131 programming spring 2001 lecture notes 3 1999-2001 s.kannan & v.tannen
DESCRIPTION
2/26/20013 Definition of Convex Hull The convex hull of a set of points S is the smallest convex region that contains the points in S. Orange points are set S. Imagine they are nails on a board. If we stretch a rubber band around S and release it, it takes the shape of the convex hull.TRANSCRIPT
2/26/2001 1
CSE 121/131
ProgrammingSpring 2001
Lecture Notes 3
1999-2001 S.Kannan & V.Tannen
2/26/2001 2
Mathematical definition
A region is convex if the line segment joiningany two points in the region is also within the region.
Examples:
convex regions
non-convex regions
2/26/2001 3
Definition of Convex HullThe convex hull of a set of points S is the smallestconvex region that contains the points in S.
Orange points are set S. Imagine they are nails on a board. Ifwe stretch a rubber band around S and release it, it takes theshape of the convex hull.
2/26/2001 4
Applications of convex hull:
Robotics: Find shortest path from point s to pointt avoiding an obstacle (on the plane).
s
t
Other applications in graphics, manufacturing,many other areas… this is a very important problem.
2/26/2001 5
Problem statementProblem: Convex Hull
Input: A set of n points on the plane.
Output: The convex hull of the points.
How is the input represented?Assume there is a class point withdata fields x and y to describe input.
How is the output described?As a list of points seen going around theconvex hull in counter-clockwise order.
2/26/2001 6
Ideas for algorithms: Line segment joining points p and q is on convex hullif every other point is on the same side of this line.
Examples:
pq
pq
not on convex hullpq pqon convex hull
2/26/2001 7
Simple algorithm
For every pair of points p, q determine the sideof that every other point r lies on. Add to list of segments to output only if all pointsr lie on same side.
pq pq
How do we talk about the “side of “ that r lies on? pq
p
qr
O
+ve side
-ve side
2/26/2001 8
Given three points p,q and r, there is an O(1) algorithmto tell if r is on the positive side of or on thenegative side of .pq
pq
In time we can determine for each pair ofpoints p,q and for each other point r, which sideof r lies on. This can be used to produce convexhull.
)( 3nO
pq
But this is too slow… can we do better?
Another idea… start with an extreme point x andkeep trying to find a next point y such that lie on the edge of convex hull. Now continue with yto find the next point z and so on.
xy
2/26/2001 9
Gift-wrapping algorithm
This algorithm can be madeto run in time…
Why?Each new point on the convexhull can be discovered in O(n)time and there are at mostO(n) points on the hull.
)( 2nO
2/26/2001 10
Graham scan algorithm
0
1
23
45
6
7
8
910
11
12
“Anchor” at extreme point.Go around in increasingorder of points.
Put points in stack aslong as we are making left turns.
If we make a right turnat some point, pop thatpoint off the stack andcheck to see if we aremaking a right turn atthe current top-of-stack.
Stack contains 1 2 3.Right turn at 3: pop 3.Stack contains 1 2 4.Stack contains 1 2 4 5.Right turn at 5: pop 5.Right turn at 4: pop 4.Stack contains 1 2 6. etc.
2/26/2001 11
Increasing order of points? What do we mean?
0
Once we anchor atlowest point 0, we wantto sort all other pointsby the slope of the linebetween that point and 0.
Assume that the point 0is at (0,0). Then theslope to point (x,y) isy/x.
We need to sort the y/x ratios. The positive ratiosrepresent points in the first quadrant and should belisted first in increasing order. The negative ratiosshould be listed from most negative to least negative.
2/26/2001 12
For each point (x,y) we can compute y/x. But we need to split them intopositive and negative ratios and thensort each of these groups separately.
How long does the algorithm take?
The sorting of about n ratios can be done in time.
Once the points are given in sorted order, theGraham scan only takes O(n) time. Why?
)log( nnO
2/26/2001 13
Another data structure: Ranked SequencesWe have seen lists, stacks, and queues. All these provide operations for inserting and/or removing elements at one or the other (or both) ends of the structure. What if we need to access, insert, and delete elements elsewhere? (The array operations do not include insert or delete.) Ranked sequences combine the conciseness of stack and queue operations with direct access as in arrays.In a sequence with n elements, each element is associated with a rank which is an integer in [0,n-1].Although the rank is like an index in an array, this does not mean that we must always implement sequences with arrays. Linked list implementations may sometimes be better.
2/26/2001 14
Ranked Sequences: the specification
public interface RankedSequence{ public Object elementAt(int i); //returns the element of rank i public void setElementAt(Object o, int i); //replaces the element of rank i with o public void insertElementAt(Object o, int i); //elements at rank i,…,n-1 move up one rank //o gets rank i public void removeElementAt(int i); //removes element at rank i //elements at rank i+1,…,n-1 move down one rank public int size(); //current number of elements public boolean isEmpty(); //test if no elements }//class ArrayIndexOutOfBoundsException //extends RuntimeException {}
2/26/2001 15
Exceptions
Checked exceptions must be declared in the method headers. Many exceptions built into Java (like ArrayIndexOutOfBounds) are unchecked because they can be thrown by many commonly used methods and it would be tedious to have to declare them.See later the throw and the try … catch syntax.
JAVA FACTSThrowable
Error Exception
RuntimeException QueueEmptyException
ArrayIndexOutOfBounds…
unchecked
MyCheckedException
MyUncheckedException checked
2/26/2001 16
Ranked Sequences: an application
RankedSequence seq = new ... // see nextfor (int i=1; i < seq.size(); i++) { Object x = seq.elementAt(i); seq.removeElementAt(i); int j = i-1; while ( j >= 0 && ((String)x).compareTo((String)seq.elementAt(j)) < 0 ) j--; seq.insertElementAt(x,j+1);}
Insertion sort is an inefficient O(n ) but easy to write sorting method. (It’s even easier with ranked sequences than with arrays since the displaced elements are moved implicitly.)
2
For simplicity, we have assumed objects of String. compareTo is a method for lexicographic ordering.
2/26/2001 17
Ranked Sequences: Vector implementationThe Java utilities package already provides a class with functionality very similar to ranked sequences: java.util.Vector The Vector operations are many, but among them are some that correspond exactly to the ones in our specification. (In fact we designed the interface with this purpose in mind, including the long name of the runtime exception the methods throw!)Vector objects are implemented with arrays. The arrays are allocated with a certain initial capacity. When that capacity fills up, the arrays are copied into bigger arrays (eg., double size) as in the implementation of stacks with arrays shown before.
2/26/2001 18
Vector implementation of RankedSequence
import java.util.Vector; class RankSeqVec extends Vector implements RankedSequence {
RankSeqVec() { // invokes Vector constructor super(12); // that sets initial capacity } // at 12, with capacity doubling} // when full
If we insist on using our interface name, we can “adapt” Vector (see later the Adapter design pattern) to produce an implementation of RankedSequence. One way to do this is to use inheritance.
2/26/2001 19
Ranked sequences with doubly linked lists
class RankSeq2Linked implements RankedSequence { private static class Cell { // static nested class Object content; Cell next; // link to next cell Cell prev; // link to previous cell Cell(Object ct, Cell n, Cell p) { content = ct; next = n; prev = p; } } private Cell header; // ref to a dummy header cell private Cell trailer; // ref to a dummy trailer private int size; // current number of elements...
Another possibility is to use linked lists, in fact doubly linked lists to facilitate traversal in both directions.
2/26/2001 20
Static nested classes
Static nested classes are used just to organize the naming space of the code. For example, Cell, its instance variables and its methods are accessible only inside class RankSeq2Linked.The methods of a static nested class can access methods and fields (and nested classes!) of the outer (enclosing) class only if these are static too. Considerclass EnclClass {... static class NestClass {... Then, outside EnclClass the nested class is referred to as EnclClass.NestClass(Later we shall encounter non-static nested classes.)
JAVA FACTS
2/26/2001 21
Using doubly linked lists, continued
RankSeq2Linked() { header = new Cell(null, null, null); trailer = new Cell(null, null, header); header.next = trailer; size = 0; } private void checkRank(int rank) { // auxiliary method if ( rank < 0 || rank > size-1 )
throw new ArrayIndexOutOfBoundsException(); }
Using two dummy cells (null content) allows for a uniform treatment of insertions and removals, regardless of whether they occur in the middle of the sequence or at some end.
2/26/2001 22
Using doubly linked lists, continued
private Cell CellAtRank(int rank) { // aux method Cell c; if (rank <= size/2 ) { // traverse forwards c = header.next; // first cell for (int i=0; i<rank; i++) c = c.next; } else { // traverse backwards c = trailer.prev; // last cell for (int i = size-1; i>rank; i--) c = c.prev; } return c; }
Given a rank, we must traverse the list counting cells to find the one corresponding to that rank.
We can halve the time (on the average) if we start at the closest end.
2/26/2001 23
Using doubly linked lists, continued
public Object elementAt(int i) throws ... { checkRank(i); return CellAtRank(i).content; } public void insertElementAt(Object o, int i) throws ... { if (i != size) // insertion at rank size is OK checkRank(i); Cell cn = CellAtRank(i) // new cell right before c Cell cp = cn.prev; // new cell right after cp Cell ic = new Cell(o, cn, cp); cp.next = ic; cn.prev = ic; size++; } The rest of the code is on the Web
site
2/26/2001 24
Design Patterns• The “adaptation” of ranked sequences from Vector that we
saw is an example of a design pattern.• Patterns address recurring design problems that arise in
specific situations. They document existing, well-proven design experience.
• Patterns provide a common vocabulary and understanding for design principles.
• Patterns are a means of documenting software architectures (even better if it is done by using some precise notations such as UML (Universal Modeling Language)
• Bibliograpy:• “A system of patterns” by Buschman et al., J.Wiley 1996.• “Design patterns” by Gamma et al., AddisonWesley 1995.
2/26/2001 25
Design Patterns, continued
• Patterns help with construction of software with defined properties, satisfying well-understood requirements.
• They help conquer complexity and heterogeneity.
• Aspects of a pattern:• Context• Problem• Solution
2/26/2001 26
The Adapter Design Pattern This is a structural pattern. It is also called wrapper (the
Java wrapper classes are adapters for the primitive types).
Context: Many!Problem: Classes that need to work together cannot
because of incompatible “signatures”. Therefore we need to convert from one class into another that clients expect.
Solution: We can make the “adaptee” a subclass of the target (as we just did with ranked sequences and Vector) but some do not consider this to be good design. Instead they recommend that the adaptee have a private field refering to a target object (more like “wrapping”). We shall illustrate this idea next by adapting ranked sequences to implement queues.
2/26/2001 27
Queues adapted from ranked sequencesclass QueueFromRankSeq implements Queue {
private RankedSequence theSeq;
public QueueFromRankSeq( ) { theSeq = new RankSeqVec(); // or any other implem } public boolean isEmpty() { return theSeq.isEmpty(); } public void enqueue( Object x ) { try { theSeq.insertElementAt(x, theSeq.size()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“should not happen”); } }...
2/26/2001 28
Adaptation, continued... public Object dequeue() throws QueueEmptyException { try { Object x = theSeq.elementAt(0); theSeq.removeElementAt(0); return x; } catch (ArrayIndexOutOfBoundsException e) { throw QueueEmptyException(); } } public Object front() throws QueueEmptyException { try { return theSeq.elementAt(0); } catch (ArrayIndexOutOfBoundsException e) { throw QueueEmptyException(); } }}
2/26/2001 29
Another design pattern: IteratorThis is a behavioral pattern. The Java Enumeration is an approximate example (the methods are a little different).
Context: Working with collections of objects.
Problem: Access the objects in a collection sequentially without exposing the underlying representation of the collection.
Solution: We build the iterators as objects associated with the collections, having access to their representation. (In Java this suggest strongly using inner classes.) The state of an iterator is given by a “cursor” referring to the current element of the collection. Iterators should have an advance method, a method to access the current element, a method to test if the whole collection was traversed, and a method to restart the traversal. Multiple iterators on the same collection are useful. Also useful is starting an iterator at some element referred to by another iterator.
2/26/2001 30
Iterator specification
public interface Iterator { // example of Iterator design pattern boolean hasMore(); // at least current element exists void next(); // advance to next element Object current(); // current element in collection void reset(); // restart at beginning Iterator spawn(); // creates new iterator, // initialized at same current element}
2/26/2001 31
Iterators for queues
... // all this is inside class QueueFromRankSeq public Iterator iter() { return new Iter(); } class Iter implements Iterator { // inner class int cursor; Iter() { cursor = 0; } public boolean hasMore() { return ( cursor != theSeq.size(); ) } ...
Imagine that the queue interface also has a method Iterator iter(). Here is the implementation of this method in the ranked sequences adapter:
2/26/2001 32
Iterators for queues, continued ... public void next() { cursor++; } public Object current() { return theSeq.elementAt(cursor); } public void reset() { cursor = 0; } public Iterator spawn() { Iter itr = new Iter(); itr.cursor = cursor; // starts in the same return itr; // place as the iterator } // who spawned it }}
2/26/2001 33
Inner classes
Non-static nested classes are called inner classes. The methods of an inner class can access fields and methods of the objects of the enclosing class. Therefore the instances (objects) of the inner class cannot exist without being attached to an enclosing instance of the outer class. Several inner instances can have the same enclosing instance. In our example, we can construct several Iter objects that enumerate the same sequence, with cursors at different positions.
JAVA FACTS
2/26/2001 34
java.util.Enumeration
public interface Enumeration { public boolean hasMoreElements(); // as in Iterator, the current element, // and maybe more exist public Object nextElement(); // return the current element // then advance to the next element // (the name chosen is not so great) }
Java comes with a simple version of the Iterator design pattern.
(Can also be implemented naturally with inner classes.)
2/26/2001 35
Using the Enumeration
public void print() { Enumeration e = elements(); System.out.print(“\n”); while (e.hasMoreElements()) System.out.print(e.nextElement() + " "); System.out.print(“\n”); }}
Assuming that queues have a method Enumeration elements() we can implement a printing method: