Problem description:
Programming assignment 2: Randomized queues and deques
Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to generics and iterators.
Dequeue.ADouble-ended queueOrDeque(Pronounced "deck") is a generalization of a stack and a queue that supports inserting and removing items from either the front or the back of the data structure. Create a generic data typeDequeThat implements the following API:
public class Deque<Item> implements Iterable<Item> { public Deque() // construct an empty deque public boolean isEmpty() // is the deque empty? public int size() // return the number of items on the deque public void addFirst(Item item) // insert the item at the front public void addLast(Item item) // insert the item at the end public Item removeFirst() // delete and return the item at the front public Item removeLast() // delete and return the item at the end public Iterator<Item> iterator() // return an iterator over items in order from front to end public static void main(String[] args) // unit testing}
ThrowNullpointerexceptionIf the client attempts to add a null item; throwJava. util. nosuchelementexceptionIf the client attempts to remove an item from an empty deque; throwUnsupportedoperationexceptionIf the client calltheRemove ()Method in the iterator; throwJava. util. nosuchelementexceptionIf the client calltheNext ()Method in the iterator and there are no more items to return.
Your deque implementation must support each deque operation inConstant worst-case timeAnd use space proportional to the number of itemsCurrentlyIn the deque. Additionally, your iterator implementation must support the operationsNext ()AndHasnext ()(Plus construction) in constant worst-case time and use a constant amount of extra space per iterator.
Randomized queue.ARandomized queueIs similar to a stack or queue, doesn't that the item removed is chosen uniformly at random from items in the data structure. Create a generic data typeRandomizedqueueThat implements the following API:
public class RandomizedQueue<Item> implements Iterable<Item> { public RandomizedQueue() // construct an empty randomized queue public boolean isEmpty() // is the queue empty? public int size() // return the number of items on the queue public void enqueue(Item item) // add the item public Item dequeue() // delete and return a random item public Item sample() // return (but do not delete) a random item public Iterator<Item> iterator() // return an independent iterator over items in random order public static void main(String[] args) // unit testing}
ThrowNullpointerexceptionIf the client attempts to add a null item; throwJava. util. nosuchelementexceptionIf the client attempts to sample or dequeue an item from an empty randomized queue; throwUnsupportedoperationexceptionIf the client calltheRemove ()Method in the iterator; throwJava. util. nosuchelementexceptionIf the client calltheNext ()Method in the iterator and there are no more items to return.
Your randomized queue implementation must support each randomized queue operation (besides creating an iterator) inConstant amortized timeAnd use space proportional to the number of itemsCurrentlyIn the queue. That is, any sequenceMRandomized queue operations (starting from an empty Queue) shocould take at mostCmSteps in the worst case, for some constantC. Additionally, your iterator implementation must support construction in time linear in the number of items and it must support the operationsNext ()AndHasnext ()In constant worst-case time; you may use a linear amount of extra memory per iterator. The order of two or more iterators to the same randomized queue shocould beMutually Independent; Each iterator must maintain its own random order.
Subset client.Write a client programSubset. JavaThat takes a command-line integerK; Reads in a sequenceNStrings from standard input usingStdin. readstring (); And prints out exactlyKOf them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 ≤K≤N, WhereNIs the number of string on standard input.
% echo A B C D E F G H I | java Subset 3 % echo AA BB BB BB BB BB CC CC | java Subset 8C BBG AAA BB CC% echo A B C D E F G H I | java Subset 3 BBE BBF CCG BB
The running time SubsetMust be linear in the size of the Input. You may use only a constant amount of memory plus either one DequeOr RandomizedqueueObject of maximum size at most n, where N is the number of strings on standard input. (For an extra challenge, use only one DequeOr RandomizedqueueObject of maximum size at most K.) It shoshould have the following API.
public class Subset { public static void main(String[] args)}
Deliverables.Submit onlyDeque. Java,Randomizedqueue. Java, AndSubset. Java. We will supplyStdlib. Jar. You may not use any libraries other than those inStdlib. Jar,Java. Lang,Java. util. iterator, AndJava. util. nosuchelementexception.
Code:
Deque. Java
import java.util.Iterator;;public class Deque<Item> implements Iterable<Item> {private Node first;private Node last;private int length;public Deque() {first = null;last = null;length = 0;}public boolean isEmpty() {return length == 0;}public int size() {return length;}public void addFirst(Item item) {if (item == null)throw new NullPointerException();if (length == 0) {Node newNode = new Node();newNode.i = item;newNode.left = null;newNode.right = null;first = newNode;last = newNode;length++;} else {Node newNode = new Node();newNode.i = item;newNode.right = null;newNode.left = first;first.right = newNode;first = newNode;length++;}}public void addLast(Item item) {if (item == null)throw new NullPointerException();if (length == 0) {Node newNode = new Node();newNode.i = item;newNode.left = null;newNode.right = null;first = newNode;last = newNode;length++;} else {Node newNode = new Node();newNode.i = item;newNode.right = last;newNode.left = null;last.left = newNode;last = newNode;length++;}}public Item removeFirst() {if (isEmpty())throw new java.util.NoSuchElementException();if (length == 1) {Item item = first.i;first = null;last = null;length--;return item;} else {Item item = first.i;Node temp = first.left;first.left.right = null;first.left = null;first = temp;length--;return item;}}public Item removeLast() {if (isEmpty())throw new java.util.NoSuchElementException();if (length == 1) {Item item = first.i;first = null;last = null;length--;return item;} else {Item item = last.i;Node temp = last.right;last.right.left = null;last.right = null;last = temp;length--;return item;}}public static void main(String[] args) {// TODO Auto-generated method stub}@Overridepublic Iterator<Item> iterator() {// TODO Auto-generated method stubreturn new ListIterator();}private class Node {private Node left;private Node right;private Item i;}private class ListIterator implements Iterator<Item> {private Node ptr;private Item i;public ListIterator(){ptr = first;}@Overridepublic boolean hasNext() {// TODO Auto-generated method stubif (ptr == null)return false;elsereturn true;}@Overridepublic Item next() {// TODO Auto-generated method stubif (!hasNext())throw new java.util.NoSuchElementException();else {i = ptr.i;ptr = ptr.left;return i;}}public void remove() {throw new UnsupportedOperationException();}}}
Randomizedqueue. Java
import java.util.Iterator;public class RandomizedQueue<Item> implements Iterable<Item> {private Item items[];private int length;public RandomizedQueue() {items = (Item[]) new Object[2];length = 0;}public boolean isEmpty() {return length == 0;}public int size() {return length;}public void enqueue(Item item) {if (item == null)throw new NullPointerException();if (length == items.length)resize(items.length * 2);items[length] = item;length++;}public Item dequeue() {if (isEmpty())throw new java.util.NoSuchElementException();int n = (int) (Math.random() * length);Item i = items[n];if (n != length - 1)items[n] = items[length - 1];length--;if (length > 0 && length == items.length / 4)resize(items.length / 2);return i;}private void resize(int n) {Item newItem[] = (Item[]) new Object[n];for (int i = 0; i < length; i++)newItem[i] = items[i];items = newItem;}public Item sample() {if (isEmpty())throw new java.util.NoSuchElementException();int n = (int) (Math.random() * length);Item i = items[n];return i;}@Overridepublic Iterator<Item> iterator() {// TODO Auto-generated method stubreturn new ListIterator();}private class ListIterator<Item> implements Iterator {int index;public ListIterator() {index = 0;}@Overridepublic boolean hasNext() {// TODO Auto-generated method stubreturn index <= length - 1;}@Overridepublic Object next() {// TODO Auto-generated method stubif (!hasNext())throw new java.util.NoSuchElementException();int n = (int) (Math.random()*(length-index));Object item = items[n];if(n != length-index-1)items[n] = items[length-index-1];index++;return item;}public void remove() {throw new UnsupportedOperationException();}}public static void main(String[] args) {// TODO Auto-generated method stub}}
Subset. Java
public class Subset {public static void main(String[] args) {// TODO Auto-generated method stubRandomizedQueue rq = new RandomizedQueue();int k = Integer.parseInt(args[0]);while (!StdIn.isEmpty())rq.enqueue(StdIn.readString());for (int i = 0; i < k; i++)StdOut.println(rq.dequeue());}}
Algorithm Part I: programming assignment (2)