package algs13;
import stdlib.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
/* ***********************************************************************
* Compilation: javac Queue.java
* Execution: java Queue < input.txt
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
*************************************************************************/
/**
* The <tt>Queue</tt> class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the top item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* All queue operations except iteration are constant time.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class Queue<T> implements Iterable<T> {
private int N; // number of elements on queue
private Node<T> first; // beginning of queue
private Node<T> last; // end of queue
// helper linked list class
private static class Node<T> {
public Node() { }
public T item;
public Node<T> next;
}
/**
* Create an empty queue.
*/
public Queue() {
first = null;
last = null;
N = 0;
}
/**
* Is the queue empty?
*/
public boolean isEmpty() {
return first == null;
}
/**
* Return the number of items in the queue.
*/
public int size() {
return N;
}
/**
* Return the item least recently added to the queue.
* @throws java.util.NoSuchElementException if queue is empty.
*/
public T peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}
/**
* Add the item to the queue.
*/
public void enqueue(T item) {
Node<T> oldlast = last;
last = new Node<>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
/**
* Remove and return the item on the queue least recently added.
* @throws java.util.NoSuchElementException if queue is empty.
*/
public T dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
T item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null;
return item;
}
/**
* Return string representation.
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
// check internal invariants
private static <T> boolean check(Queue<T> that) {
int N = that.N;
Queue.Node<T> first = that.first;
Queue.Node<T> last = that.last;
if (N == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (N == 1) {
if (f.
1. package algs13;
import stdlib.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
/*
*****************************************************
******************
* Compilation: javac Queue.java
* Execution: java Queue < input.txt
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
*****************************************************
********************/
/**
* The <tt>Queue</tt> class represents a first-in-first-out
(FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and
<em>dequeue</em>
* operations, along with methods for peeking at the top item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* All queue operations except iteration are constant time.
* <p>
* For additional documentation, see <a
href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a>
of
2. * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and
Kevin Wayne.
*/
public class Queue<T> implements Iterable<T> {
private int N; // number of elements on queue
private Node<T> first; // beginning of queue
private Node<T> last; // end of queue
// helper linked list class
private static class Node<T> {
public Node() { }
public T item;
public Node<T> next;
}
/**
* Create an empty queue.
*/
public Queue() {
first = null;
last = null;
N = 0;
}
/**
* Is the queue empty?
*/
public boolean isEmpty() {
return first == null;
}
/**
* Return the number of items in the queue.
*/
public int size() {
return N;
3. }
/**
* Return the item least recently added to the queue.
* @throws java.util.NoSuchElementException if queue is
empty.
*/
public T peek() {
if (isEmpty()) throw new
NoSuchElementException("Queue underflow");
return first.item;
}
/**
* Add the item to the queue.
*/
public void enqueue(T item) {
Node<T> oldlast = last;
last = new Node<>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
/**
* Remove and return the item on the queue least recently
added.
* @throws java.util.NoSuchElementException if queue is
empty.
*/
public T dequeue() {
if (isEmpty()) throw new
NoSuchElementException("Queue underflow");
T item = first.item;
4. first = first.next;
N--;
if (isEmpty()) last = null;
return item;
}
/**
* Return string representation.
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
// check internal invariants
private static <T> boolean check(Queue<T> that) {
int N = that.N;
Queue.Node<T> first = that.first;
Queue.Node<T> last = that.last;
if (N == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (N == 1) {
if (first == null || last == null) return false;
if (first != last) return false;
if (first.next != null) return false;
}
else {
if (first == last) return false;
if (first.next == null) return false;
if (last.next != null) return false;
// check internal consistency of instance variable
5. N
int numberOfNodes = 0;
for (Queue.Node<T> x = first; x != null; x =
x.next) {
numberOfNodes++;
}
if (numberOfNodes != N) return false;
// check internal consistency of instance variable
last
Queue.Node<T> lastNode = first;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
if (last != lastNode) return false;
}
return true;
}
/**
* Return an iterator that iterates over the items on the
queue in FIFO order.
*/
public Iterator<T> iterator() {
return new ListIterator();
}
// an iterator, doesn't implement remove() since it's
optional
private class ListIterator implements Iterator<T> {
private Node<T> current = first;
public boolean hasNext() { return current != null;
}
6. public void remove() { throw new
UnsupportedOperationException(); }
public T next() {
if (!hasNext()) throw new
NoSuchElementException();
T item = current.item;
current = current.next;
return item;
}
}
public void toGraphviz(String filename) {
GraphvizBuilder gb = new GraphvizBuilder ();
toGraphviz (gb, null, first);
gb.toFile (filename, "rankdir="LR"");
}
private void toGraphviz (GraphvizBuilder gb, Node<T>
prev, Node<T> n) {
if (n == null) { gb.addNullEdge (prev); return; }
gb.addLabeledNode (n, n.item.toString ());
if (prev != null) gb.addEdge (prev, n);
toGraphviz (gb, n, n.next);
}
/**
* A test client.
*/
public static void main(String[] args) {
StdIn.fromString ("to be or not to - be - - that - - -
is");
Queue<String> q = new Queue<>();
int count = 0;
q.toGraphviz ("queue" + count + ".png"); count++;
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
7. if (!item.equals("-")) q.enqueue(item);
else if (!q.isEmpty()) StdOut.print(q.dequeue() +
" ");
q.toGraphviz ("queue" + count + ".png");
count++;
}
StdOut.println("(" + q.size() + " left on queue)");
}
}
package algs24;
import stdlib.*;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/*
*****************************************************
******************
* Compilation: javac MinPQ.java
* Execution: java MinPQ < input.txt
*
* Generic min priority queue implementation with a binary
heap.
* Can be used with a comparator instead of the natural order,
* but the generic key type must still be Comparable.
*
* % java MinPQ < tinyPQ.txt
* E A E (6 left on pq)
*
* We use a one-based array to simplify parent and child
calculations.
*
*****************************************************
********************/
8. /**
* The <tt>MinPQ</tt> class represents a priority queue of
generic keys.
* It supports the usual <em>insert</em> and <em>delete-the-
minimum</em>
* operations, along with methods for peeking at the maximum
key,
* testing if the priority queue is empty, and iterating through
* the keys.
* <p>
* The <em>insert</em> and <em>delete-the-minimum</em>
operations take
* logarithmic amortized time.
* The <em>min</em>, <em>size</em>, and <em>is-
empty</em> operations take constant time.
* Construction takes time proportional to the specified
capacity or the number of
* items used to initialize the data structure.
* <p>
* This implementation uses a binary heap.
* <p>
* For additional documentation, see <a
href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and
Kevin Wayne.
*/
public class MinPQ<K extends Comparable<? super K>>
implements Iterable<K> {
private K[] pq; // store items at indices 1 to N
private int N; // number of items on priority
queue
private Comparator<? super K> comparator; // optional
comparator
// helper function to double the size of the heap array
9. @SuppressWarnings("unchecked")
private void resize(int capacity) {
if (capacity <= N) throw new
IllegalArgumentException ();
K[] temp = (K[]) new Comparable[capacity];
for (int i = 1; i <= N; i++) temp[i] = pq[i];
pq = temp;
}
@SuppressWarnings("unchecked")
/** Create an empty priority queue with the given initial
capacity, using the given comparator. */
public MinPQ(int initCapacity, Comparator<? super K>
comparator) {
pq = (K[]) new Comparable[initCapacity + 1];
N = 0;
this.comparator = comparator;
}
/** Create an empty priority queue with the given initial
capacity. */
public MinPQ(int initCapacity) { this(initCapacity, null); }
/** Create an empty priority queue using the given
comparator. */
public MinPQ(Comparator<? super K> comparator) {
this(1, comparator); }
/** Create an empty priority queue. */
public MinPQ() { this(1, null); }
/**
* Create a priority queue with the given items.
* Takes time proportional to the number of items using
sink-based heap construction.
*/
public MinPQ(K[] keys) {
this(keys.length, null);
N = keys.length;
10. for (int i = 0; i < N; i++)
pq[i+1] = keys[i];
for (int k = N/2; k >= 1; k--)
sink(k);
//assert isMinHeap();
}
/** Is the priority queue empty? */
public boolean isEmpty() { return N == 0; }
/** Return the number of items on the priority queue. */
public int size() { return N; }
/**
* Return the smallest key on the priority queue.
* @throws java.util.NoSuchElementException if the
priority queue is empty.
*/
public K min() {
if (isEmpty()) throw new
NoSuchElementException("Priority queue underflow");
return pq[1];
}
/** Add a new key to the priority queue. */
public void insert(K x) {
// double size of array if necessary
if (N >= pq.length - 1) resize(2 * pq.length);
// add x, and percolate it up to maintain heap
invariant
pq[++N] = x;
swim(N);
//assert isMinHeap();
}
11. /**
* Delete and return the smallest key on the priority queue.
* @throws java.util.NoSuchElementException if the
priority queue is empty.
*/
public K delMin() {
if (isEmpty()) throw new
NoSuchElementException("Priority queue underflow");
exch(1, N);
K min = pq[N--];
sink(1);
pq[N+1] = null; // avoid loitering and help with
garbage collection
if ((N > 0) && (N == (pq.length - 1) / 4))
resize(pq.length / 2);
//assert isMinHeap();
return min;
}
/*
*****************************************************
****************
* Helper functions to restore the heap invariant.
*****************************************************
*****************/
private void swim(int k) {
while (k > 1 && greater(k/2, k)) {
exch(k, k/2);
k = k/2;
}
}
private void sink(int k) {
12. while (2*k <= N) {
int j = 2*k;
if (j < N && greater(j, j+1)) j++;
if (!greater(k, j)) break;
exch(k, j);
k = j;
}
}
/*
*****************************************************
****************
* Helper functions for compares and swaps.
*****************************************************
*****************/
private boolean greater(int i, int j) {
if (comparator == null) {
return pq[i].compareTo(pq[j]) > 0;
}
else {
return comparator.compare(pq[i], pq[j]) > 0;
}
}
private void exch(int i, int j) {
K swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
}
// is pq[1..N] a min heap?
private boolean isMinHeap() {
return isMinHeap(1);
}
13. // is subtree of pq[1..N] rooted at k a min heap?
private boolean isMinHeap(int k) {
if (k > N) return true;
int left = 2*k, right = 2*k + 1;
if (left <= N && greater(k, left)) return false;
if (right <= N && greater(k, right)) return false;
return isMinHeap(left) && isMinHeap(right);
}
/*
*****************************************************
****************
* Iterator
*****************************************************
*****************/
/**
* Return an iterator that iterates over all of the keys on
the priority queue
* in ascending order.
* <p>
* The iterator doesn't implement <tt>remove()</tt> since
it's optional.
*/
public Iterator<K> iterator() { return new HeapIterator(); }
private class HeapIterator implements Iterator<K> {
// create a new pq
private MinPQ<K> copy;
// add all items to copy of heap
// takes linear time since already in heap order so no
keys move
public HeapIterator() {
14. if (comparator == null) copy = new
MinPQ<K>(size());
else copy = new MinPQ<K>(size(),
comparator);
for (int i = 1; i <= N; i++)
copy.insert(pq[i]);
}
public boolean hasNext() { return !copy.isEmpty();
}
public void remove() { throw new
UnsupportedOperationException(); }
public K next() {
if (!hasNext()) throw new
NoSuchElementException();
return copy.delMin();
}
}
void showHeap() {
for (int i = 1; i <= N; i++)
StdOut.print (pq[i] + " ");
StdOut.println ();
}
/**
* A test client.
*/
public static void main(String[] args) {
MinPQ<String> pq = new MinPQ<>(100);
StdIn.fromString ("10 20 30 40 50 - - - 05 25 35 - - -
70 80 05 - - - - ");
while (!StdIn.isEmpty()) {
StdOut.print ("pq: "); pq.showHeap();
String item = StdIn.readString();
15. if (item.equals("-")) StdOut.println("min: " +
pq.delMin());
else pq.insert(item);
GraphvizBuilder.binaryHeapToFile (pq.pq,
pq.N);
}
StdOut.println("(" + pq.size() + " left on pq)");
}
}
package finalexam;
/*
* This class is a program class that tests the
* various methods and classes written for the CSC
* 300 final exam for Spring, 2017. It was written
* by John Rogers.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
16. import stdlib.StdIn;
import stdlib.StdOut;
import algs13.Queue;
public class TestFinal {
public static <Item extends Comparable<? super Item>>
boolean isSorted(Item[] a) {
for (int i = 0; i < a.length-1; i++) {
if (a[i].compareTo(a[i+1]) > 0) return false;
}
return true;
}
public static void main(String[] args) {
StdOut.println("*** " + Final.yourName() + " ***");
StdOut.println();
17. Integer[] array = new Integer[12];
Random r = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = r.nextInt(1000);
}
StdOut.println("Array before sorting: " +
Arrays.toString(array));
Final.minpqSort(array);
StdOut.println("Array after sorting: " +
Arrays.toString(array));
StdOut.println("Array is sorted: " + isSorted(array));
StdOut.println();
Queue<String> queue = new Queue<String>();
queue.enqueue("first");
queue.enqueue("second");
queue.enqueue("third");
queue.enqueue("fourth");
18. StdOut.println("Queue before reversing: " + queue);
Final.reverseQueue(queue);
StdOut.println("Queue after reversing: " + queue);
StdOut.println();
double[] frequencies = {110.0, 110.0*1.224,
110.0*1.224*1.224};
ArrayList<Chord> risingChords =
Final.createRisingChordList(0.2, frequencies, 10);
for (Chord risingChord: risingChords) {
StdOut.println("Playing: " + risingChord);
risingChord.play();
}
StdOut.println();
ArrayList<CTATrain> ctaTrains = new
ArrayList<CTATrain>();
StdIn.fromFile("data/CTAdata.txt");
while (!StdIn.isEmpty()) {
19. int runNumber = StdIn.readInt();
String lineColor = StdIn.readString();
String nextStation = StdIn.readString();
String arrivalTime = StdIn.readString();
ctaTrains.add(new CTATrain(runNumber,
lineColor, nextStation, arrivalTime));
}
StdOut.println("--- Trains before sorting ---");
for (CTATrain ctaTrain: ctaTrains) {
StdOut.println(ctaTrain);
}
StdOut.println();
ctaTrains.sort(null);
StdOut.println("--- Trains after sorting by run number
---");
for (CTATrain ctaTrain: ctaTrains) {
StdOut.println(ctaTrain);
}
20. StdOut.println();
ctaTrains.sort((CTATrain t1, CTATrain t2) ->
(t1.getArrivalTime().compareTo(t2.getArrivalTime())));
StdOut.println("--- Trains after sorting by arrival time
---");
for (CTATrain ctaTrain: ctaTrains) {
StdOut.println(ctaTrain);
}
StdOut.println();
StdOut.println("=== " + Final.yourName() + " ===");
}
}
CSC 300/Data Structures I
Final exam
85 points
21. Instructions
1. In Eclipse, create a package called finalexam.
2. Download and place into the package the file TestFinal.java.
3. Copy into the package the Chord class you created in an
earlier assignment.
4. In the package, create a class called Final. All of the static
methods you are asked to write will go in this class.
5. You will also eventually add to the package a reference class
called CTATrain.
The first problem (your name) is worth 5 points; each of the
other four are worth 20 points.
Your name
Define and place into the Final class a method with the
signature:
public static String yourName()
that returns a string containing your name in the format
"lastname, firstname". For example, for me the method would
return the string
"Rogers, John".
Priority queue
In the package algs24, you will find a class MinPQ, which
implements a minimum priority queue. You are to use it to
define in the Final class a
generic sort method with the signature:
public static <Item extends Comparable<? super Item>> void
minpqSort(Item[] a)
22. The code in the method should:
1. Create a MinPQ object. This class implements a minimum
priority queue and is found in the algs24 package.
2. Insert each value in the parameter array into the min priority
queue.
3. Using the delMin method, remove values from the min
priority queue and place them into the array, overwriting the
values that were there.
Done correctly, the array will now be sorted in ascending order.
FIFO Queue
Define in the Final class a generic method called reverseQueue
with the signature:
public static <Item> Queue<Item> reverseQueue(Queue<Item>
queue)
It modifies its parameter so that, when it returns, the values in
the queue are reversed. For example, if the queue q1 contains
the integer values 13,
15, 9, 10, and 25 (in that order), the following call:
q2 = reverseQueue(q1);
will result in q2 having the values 25, 10, 9, 15, 13 (in that
order).
Use the queue class defined in algs13.
Reference class
Write a reference class called CTATrain that models
information about a CTA "L" train making its run. The instance
23. variables should contain
information about the train's:
run number, an integer;
line color, a string containing one of the values "red", "green",
"blue", "purple", "brown", "pink", "orange", or "yellow";
next station, a string containing the name of the station it will
next arrive at;
arrival time, a string of the form "hh:mm:ss" indicating when it
is expected to arrive at that station.
The API consists of:
a four-parameter constructor;
individual methods for retrieving the value of each instance
variable (i.e., accessor methods). For example, the signature of
the one retrieving
the line color will be public String getLineColor()
toString() method that produces a string looking like this:
[brown, 421, Rockwell, 13:34:54>, where the values are the line
color,
run number, next station, and arrival time;
compareTo(CTATrain that) method that compares CTA train
objects based on their run number, which means you should
define the
class so that CTATrain objects are comparable.
The test program has been written to read data from the file
CTAdata.txt. Place this in your data folder in Eclipse. The test
program then sorts an
file:///Users/Woody/Downloads/Final%20exam%20(1)/TestFinal
.java
file:///Users/Woody/Downloads/Final%20exam%20(1)/CTAdata
.txt
24. array list of trains in a couple of different ways, each time
printing the list.
Swan song
Using the Chord class you created in a previous assignment,
define in the Final class a method with the signature
public static ArrayList<Chord> createRisingChordList(double
duration, double[] frequencies, int count)
that creates, fills, and returns an array list of Chord objects. It
will fill it with count chords. Every chord will have the duration
specified. The first
chord will have the frequencies specified in the parameters. The
next chord is formed by multiplying each entry in the
frequencies array by the value
1.224. So you'll have a loop that:
1. creates a chord from the duration and frequencies;
2. adds it to the array list
3. updates every value in the frequencies array by multiplying it
by 1.224;
Follow that with a loop that plays the chords using the play()
instance method in the Chord class.
Testing your code
The TestFinal program will test every one of your methods and
classes. It produces (a lot) of output and it will be obvious
whether your code
works.
Submission instructions
25. Your finalexam package should contains three files:
1. Final.java, which contains the static methods your wrote;
2. CTATrain.java, which is the reference class you wrote for
this exam;
3. Chord.java, which is the reference class written for a
previous assignment;
It is not necessary to include the TestFinal.java program class.
If you do, that's fine but when grading, I'll use my own copy.
Please do not place
the CTA train data file in the package!
As usual, zip the package folder containing these files into a zip
file called finalexam.zip (and NOT finalexam.java.zip or some
other variation!).
Please MAKE SURE the package folder is zipped with the files!
Submit the zip file into the drop box provided.
Last update: June 1st, 2017
415 brown Merchandise-Mart 16:15:54
414 brown Merchandise-Mart 16:18:48
504 purple Merchandise-Mart 16:19:59
513 purple Merchandise-Mart 16:21:57
425 brown Merchandise-Mart 16:21:00
416 brown Merchandise-Mart 16:25:45
422 brown Merchandise-Mart 16:26:37
26. 415 brown Merchandise-Mart 16:31:54
505 purple Merchandise-Mart 16:31:31
411 brown Merchandise-Mart 16:31:55
513 purple Adams/Wabash 16:14:57
614 green Adams/Wabash 16:16:12
310 pink Adams/Wabash 16:17:29
720 orange Adams/Wabash 16:18:52
422 brown Adams/Wabash 16:19:37
008 green Adams/Wabash 16:21:49
007 green Adams/Wabash 16:22:50
415 brown Adams/Wabash 16:24:54
504 purple Adams/Wabash 16:25:59
315 pink Adams/Wabash 16:26:00