Subset client. Write a client program Subset.java that takes a command-line integer k; reads in a sequence of N strings from standard input using StdIn.readString(); and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 ≤ k ≤ N, where N is 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 8
C BB
G AA
A BB
CC
% echo A B C D E F G H I | java Subset 3 BB
E BB
F CC
G BB
The running time of
Subset must be linear in the size of the input. You may use only a constant amount of memory plus either one
Deque or
RandomizedQueue object of maximum size at most N, where N is the number of strings on standard input. (For an extra challenge, use only one
Deque or
RandomizedQueue object of maximum size at most k.) It should have the following API.
public class Subset {
public static void main(String[] args)
}
Deliverables. Submit only Deque.java, RandomizedQueue.java, and Subset.java. We will supply stdlib.jar. You may not use any libraries other than those in stdlib.jar, java.lang, java.util.Iterator, and java.util.NoSuchElementException.
代码:
Deque.java
import java.util.Iterator; ; public class Deque- implements Iterable
- { 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;