// 封装队列(基于数组)
class Queue {
// 属性
items = [];
// 方法
// 1.将元素加入到队列中
enqueue(element: any) {
this.items.push(element);
}
// 2.从队列中删除前端元素
dequeue() {
return this.items.shift();
}
// 3.查看队列前端元素
front() {
return this.items[0];
}
// 4.查看队列是否为空
isEmtpy() {
return this.items.length === 0;
}
// 5.查看队列中元素的个数
size() {
return this.items.length;
}
// 6.tostring方法
toString() {
return this.items.toString();
}
}
/**
* 游戏规则:
* 几个朋友一起玩一个游戏, 围成一圈, 开始数数(数数时数字都是挨着的,
* 第一个人数1,之后的人数2), 数到某个数字的人自动淘汰。淘汰的人后
* 面再从1开始数,重复上面的游戏,直到就剩下一个人,请问剩下了谁?
*/
/**
*
* @param nameList 参与游戏的姓名
* @param num 指定的数字
*/
const passGame = (nameList: Array<string>, num: number) => {
// 1.首先new一个队列
const gamePersonnel = new Queue();
// 2.把所有玩游戏的人加入到队列当中
for (let i = 0; i < nameList.length; i++) {
gamePersonnel.enqueue(nameList[i]);
}
// 3.开始数数字
// 3-3.当参与游戏的玩家不大于1的时候就跳出循环
while (gamePersonnel.size() > 1) {
for (let i = 0; i < num - 1; i++) {
// 3-1.将所有已经数过数字(不是num)的玩家姓名依次添加到队列末尾
gamePersonnel.enqueue(gamePersonnel.dequeue());
}
// 3-2.然后队列第一个就是喊到num的玩家(删除他即刻) 那么什么时候就不删除了呢?
gamePersonnel.dequeue();
}
console.log(`还剩下${gamePersonnel.size()}个玩家`);
const winName = gamePersonnel.front();
console.log(`最终获得胜利的是${winName}`);
console.log(`他是第${nameList.indexOf(winName) + 1}个入场的玩家`);
}
const names = ['forward', 'iwen', 'tom', 'liming', 'ime', 'andy'];
passGame(names, 3);