-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue-circular-fixed-size-array.js
69 lines (57 loc) · 1.38 KB
/
queue-circular-fixed-size-array.js
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
class Queue {
constructor(capacity = 10){
this.capacity = capacity;
this.queue = new Array(this.capacity);
this.left = -1;
this.right = -1;
this.length = 0;
}
isEmpty(){
return this.length == 0;
}
isFull(){
return (this.right + 1) % this.capacity == this.left;
}
size(){
return this.length;
}
enqueue(item){
if(this.isFull()){
throw new Error('Queue is full');
}
if(this.left == -1){
this.left = 0;
}
this.right = (this.right + 1) % this.capacity;
this.queue[this.right] = item;
this.length++;
}
dequeue(){
if(this.isEmpty()){
throw new Error('Queue is empty');
}
let item = this.queue[this.left];
if(this.left == this.right){
this.left = this.right = 1;
}
else{
this.left = (this.left + 1) % this.capacity;
}
this.length--;
return item;
}
}
function hotPotato(people, n){
let q = new Queue(10);
for(person of people){
q.enqueue(person);
}
while(q.size() > 1){
for(let i = 0; i < n; i++){
q.enqueue(q.dequeue());
}
q.dequeue();
}
return q.dequeue();
}
console.log(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"],7));