击鼓传花(HotPotato)游戏,在这个游戏中,孩子们围成一个圆圈,把花尽快地传递给旁边的人。某一时刻传花停止,这个时候花在谁手里,谁就退出圆圈结束游戏。重复这个过程,直到只剩一个孩子(胜者)。
function Queue() {
this.database = [];
this.enqueue = function(ele){
this.database.push(ele);
};
this.dequeue = function(){
return this.database.shift();
};
this.front = function(){
return this.database[0]
}
this.back = function(){
this.database[this.database.length-1];
};
this.toString = function(){
var str = '';
for (var i = 0; i < this.database.length; i++) {
str += this.database[i] + '\n';
}
return str;
};
this.empty = function(){
return (this.database.length == 0) ? true : false;
};
this.size = function(){
return this.database.length;
};
}
function hotPotato (nameList, num){
let queue = new Queue();
for (let i=0; i<nameList.length; i++){
queue.enqueue(nameList[i]);
}
let eliminated = '';
while (queue.size() > 1){
for (let i=0; i<num; i++){
queue.enqueue(queue.dequeue());
}
console.log(queue.dequeue() + '在击鼓传花游戏中被淘汰。');
}
return queue.dequeue();
}
let names = ['John','Jack','Camila','Ingrid','Carl'];
let winner = hotPotato(names,7);
console.log('胜利者:' + winner);