游戏规则:所有人排成一圈,班长负责击鼓,击鼓后开始依次传花,鼓声停止花传到谁谁就被淘汰,剩下的最后一个人为获胜。
这里规则做一下修改,改成数数,比如我们规定一个数字5,所有人依次从1开始数数字,数到5的那个人则被淘汰,被淘汰的下一个人重新从1开始数数,以此类推。。。
解题思路:这里可以应用队列来解决,数到5的人从队列中删除,直到剩下最后一个人则获胜(队列先进先出)。
// 首先实现一个队列函数 function Queue(){ this.items = [] // 添加元素入队列 Queue.prototype.add = function(item){ this.items.push(item) } // 删除队列第一个元素 Queue.prototype.del = function(){ return this.items.shift() } // 查看队列第一个元素 Queue.prototype.front = function(){ return this.items[0] } // 查看队列长度 Queue.prototype.size = function(){ return this.items.length } // 队列是否为空 Queue.prototype.isEmpty = function(){ return this.items.length === 0 } // 实现tostring方法 Queue.prototype.toString = function(){ let itemString = '' for(var i=0;i<this.items.length;i++){ itemString+=this.items[i]+" " } return itemString } } // 解题: function overGame(nameList=[],num=0){ var nqueue = new Queue() for(var i=0;i<nameList.length;i++){ nqueue.add(nameList[i]) } while(nqueue.size()>1){ for(var i=0;i<num-1;i++){ nqueue.add(nqueue.del()) } nqueue.del() } return { value: nqueue.front(), // 获胜者 index: nameList.indexOf(nqueue.front()) // 获胜者的最初位置 } }