击鼓传花模拟循环队列

date
Mar 13, 2023
slug
js-two-ended-queue-beat
status
Published
tags
JavaScript数据结构与算法
Queue
JavaScript
summary
Apply beat the drum and pass the flowers whit two-ended-queue
type
Post
在这个游戏中,孩子们围成一个圆圈,把花尽快地传递给旁边的人。某一时刻传花停止, 这个时候花在谁手里,谁就退出圆圈、结束游戏。重复这个过程,直到只剩一个孩子(胜者)。
class Queue{
    constructor(){
        this.count = 0;
        this.lowestCount = 0;
        this.items = {};
    }
    enqueue(element){
        this.items[this.count] = element;
        this.count++;
    }
    isEmpty(){
        return this.count - this.lowestCount === 0;
    }
    size(){
        return this.count - this.lowestCount;
    }
    dequeue(){
        if(this.isEmpty()){
            return undefined;
        }
        const re = this.items[this.lowestCount];
        delete this.items[this.lowestCount];
        this.lowestCount ++;
        return re;
    }
}

function hotPotato(elementsList, num) { 
 const queue = new Queue(); //实现Queue类
 const elimitatedList = []; 
 
 //把所有人的名字加入队列中
 for (let i = 0; i < elementsList.length; i++) { 
   queue.enqueue(elementsList[i]); 
 } 
 while (queue.size() > 1) { 
     //给定一个数字,然后迭代队列。从队列开头移除一项,再将其添加到队列末尾
  for (let i = 0; i < num; i++) { 
      //模拟击鼓传花(如果你把花传给了旁边的人,你被淘汰的威胁就立刻解除了)。
    queue.enqueue(queue.dequeue());
  } 
     //一旦达到给定的传递次数,拿着花的那个人就被淘汰
  elimitatedList.push(queue.dequeue()); 
 } 
 return { 
 eliminated: elimitatedList, 
     //最后只剩下一个人的时候,这个人就是胜者
 winner: queue.dequeue() 
 }; 
} 

const names = ['John', 'Jack', 'Camila', 'Ingrid', 'Carl']; 
const result = hotPotato(names, 7);

result.eliminated.forEach(name => { 
 console.log(`${name}在击鼓传花游戏中被淘汰。`); 
}); 
console.log(`胜利者: ${result.winner}`);
输出结果如下:
Camila 在击鼓传花游戏中被淘汰。
Jack 在击鼓传花游戏中被淘汰。
Carl 在击鼓传花游戏中被淘汰。
Ingrid 在击鼓传花游戏中被淘汰。
胜利者:John
模拟过程:
notion image
 

© shallrise 2025