-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
96 lines (83 loc) · 1.97 KB
/
queue.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
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
/*
* @Author: your name
* @Date: 2021-04-16 14:58:45
* @LastEditTime: 2021-08-11 18:34:16
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \code\queue.js
*/
class queue{
constructor(){
this.item=[];
}
enqueue(e){
this.item.push(e)
}
dequeue(){
this.item.shift()
}
front(){
return this.item[0]
}
size(){
return this.item.length
}
isEmpty(){
return this.item.length === 0
}
}
function QueueElement(e,p){
this.element=e;
this.priority=p;
}
//优先级队列
class priorityQueue{
constructor(){
this.item=[]
}
enqueue(e,p){
const ep= new QueueElement(e,p)
if(isEmpty(this.item)){
return this.item.push(ep)
}else{
let isAdd = false;
for(let i=0;i<this.item.length;i++){
//数字越小优先级越高
if(this.item[i].priority > ep.priority){
this.item.splice(i,0,ep);
isAdd=true
}
break
}
if(!isAdd){
return this.item.push(ep)
}
}
}
dequeue(){
return this.item.shift()
}
front(){
return this.item[0]
}
size(){
return this.item.length
}
isEmpty(){
return this.item.length === 0
}
}
//击鼓传花游戏
//规则:几个朋友一起玩一个游戏, 围成一圈, 开始数数, 数到某个数字的人自动淘汰.
function game(names,num){
const gameQueue=new queue();
names.map(v => gameQueue.enqueue(v))
while(gameQueue.size() > 1){
for(let i=0;i<num;i++){
gameQueue.enqueue(gameQueue.dequeue())
}
gameQueue.dequeue()
}
const end = gameQueue.dequeue()
return names.indexOf(end)
}