-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizedQueue.java
More file actions
91 lines (83 loc) · 2.93 KB
/
RandomizedQueue.java
File metadata and controls
91 lines (83 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int initSize = 1;
private int queueSize = 0;
private Item[] queue;
public RandomizedQueue() { // construct an empty randomized queue
queue = (Item[]) new Object[initSize];
}
public boolean isEmpty() { // is the randomized queue empty?
return queueSize == 0;
}
public int size() { // return the number of items on the randomized queue
return queueSize;
}
private void resize(int size) {
Item[] temp = (Item[]) new Object[size];
for (int i = 0; i < queueSize; i++)
temp[i] = queue[i];
queue = temp;
}
public void enqueue(Item item) { // add the item
if (item == null) {
throw new java.lang.IllegalArgumentException();
}
if (queueSize == queue.length) {
resize(2*queue.length);
}
queue[queueSize++] = item;
}
public Item dequeue() { // remove and return a random item
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
int randomIndex = StdRandom.uniform(queueSize);
Item item = queue[randomIndex];
if (randomIndex != queueSize) {
queue[randomIndex] = queue[queueSize-1];
}
queue[queueSize-1] = null;
queueSize--;
if (queueSize < queue.length/4) {
resize(queue.length/2);
}
return item;
}
public Item sample() { // return a random item (but do not remove it)
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
int randomIndex = StdRandom.uniform(queueSize);
return queue[randomIndex];
}
private class ArrayIterator implements Iterator<Item> {
private int index = 0;
private int[] randomInt;
public ArrayIterator() {
randomInt = new int[queueSize];
for (int i = 0; i < randomInt.length; i++)
randomInt[i] = i;
StdRandom.shuffle(randomInt);
}
public boolean hasNext() {
return (index < queue.length);
}
public Item next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
int randomIndex = randomInt[index];
index++;
return queue[randomIndex];
}
public void remove() {
throw new java.lang.UnsupportedOperationException();
}
}
public Iterator<Item> iterator() { // return an independent iterator over items in random order
return new ArrayIterator();
}
public static void main(String[] args) { // unit testing (optional)
}
}