-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizedQueue.java
More file actions
107 lines (89 loc) · 2.82 KB
/
RandomizedQueue.java
File metadata and controls
107 lines (89 loc) · 2.82 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException;
/*
This class creates a randomized queue. Essentially, adds elements to
the Queue and removes elements such that
the removal is uniformly random.
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] arr;
private int size;
public RandomizedQueue() {
arr = (Item[]) new Object[1];
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void enqueue(Item item) {
if (item == null) throw new IllegalArgumentException();
if (size == arr.length) grow();
arr[size++] = item;
}
// Helper function to grow the array. With this approach,
// insertion is an amortized O(1) operation. Doubles when array is full.
private void grow() {
Item[] newArr = (Item[]) new Object[2 * arr.length];
int counter = 0;
for (Item it : arr) newArr[counter++] = it;
arr = newArr;
}
public Item dequeue() {
if (size == 0) noSuchElem();
// Checks whether number of elements falls beneath a quarter of array size.
if (size * 4 == arr.length && size > 0) shrink();
int rand = StdRandom.uniform(size);
Item temp = arr[rand];
arr[rand] = arr[size - 1];
arr[size - 1] = null;
size--;
return temp;
}
// Helper function to shrink array when necessary. Cuts array in half.
private void shrink() {
Item[] newArr = (Item[]) new Object[(int) (1 / 2.0 * arr.length)];
for (int counter = 0; counter < size; counter++) {
newArr[counter] = arr[counter];
}
arr = newArr;
}
public Item sample() {
if (size == 0) noSuchElem();
return arr[StdRandom.uniform(size)];
}
// Helper function for when no element is available.
private void noSuchElem() {
throw new NoSuchElementException();
}
public Iterator<Item> iterator() {
return new RandIterator();
}
/*
Iterator class that iterates over the queue in a uniformly
random order.
*/
private class RandIterator implements Iterator<Item> {
RandomizedQueue<Item> tempQ;
public RandIterator() {
tempQ = new RandomizedQueue<>();
for (int i = 0; i < size; i++) {
tempQ.enqueue(arr[i]);
}
}
public boolean hasNext() {
return tempQ.size() != 0;
}
public Item next() {
if (tempQ.size() == 0) noSuchElem();
return tempQ.dequeue();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}