/
RandomizedQueue.ts
87 lines (71 loc) · 1.56 KB
/
RandomizedQueue.ts
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
// doubly linked list with random insetion and random sampling
class RandomizedQueue<T> {
head: Item<T>;
tail: Item<T>;
numItems: number;
constructor() {
this.head = null;
this.tail = null;
this.numItems = 0;
}
isEmpty(): boolean {
return this.head === null;
}
size(): number {
return this.numItems;
}
enqueue(item: T): void {
const newItem = new Item<T>(item);
if (!this.head) {
this.head = newItem;
this.tail = newItem;
} else {
this.tail.next = newItem;
newItem.prev = this.tail;
this.tail = newItem;
}
}
dequeue(): T {
if (!this.head) return null;
let randomIndex = Math.floor(Math.random() * this.numItems);
let current = this.head;
while (randomIndex > 0) {
current = current.next;
randomIndex -= 1;
}
if (current === this.head) {
this.head = current.next;
}
if (current === this.tail) {
this.tail = current.prev;
}
const prev = current.prev;
prev.next = current.next;
current.prev = prev;
return current.value;
}
sample(): T {
let randomIndex = Math.floor(Math.random() * this.numItems);
let current = this.head;
while (randomIndex > 0) {
current = current.next;
randomIndex -= 1;
}
return current.value;
}
*[Symbol.iterator]() {
// Haven't figured it out
yield 1;
}
}
class Item<T> {
value: T;
next: Item<T>;
prev: Item<T>;
constructor(value: T) {
this.value = value;
this.next = null;
this.prev = null;
}
}
export default RandomizedQueue;