JavaScript实现:n个人中,数到某一数字就退出游戏

107 阅读1分钟

基本思路:把n个人在一个队列中,从队头开始依次计数,不是这个数字时就将其放到队尾,遇到就将其移出队列。

function Queue(initQueue) {
  this.queue = initQueue || []
  this.length = (initQueue && initQueue.length) || 0
  
  // 添加节点到队列尾部
  Queue.prototype.add = function (item) {
    this.queue.push(item)
    this.length++
    return this
  }
  // 移除队列头部节点
  Queue.prototype.remove = function () {
    const removed = this.queue.shift()
    this.length--
    return removed
  }
  // 移动队列头部到尾部
  Queue.prototype.headToEnd = function () {
    const head = this.remove()
    return this.add(head)
  }
}

// queue: n个人的数组
// n: 到这个数字就退出游戏
function playGames(queue, n) {
  que = new Queue(queue)

  while (que.length > 1) {
    for (let i = 1; i < n; i++) {
      que.headToEnd()
    }
    // 每到第 n 个就移出队列
    que.remove()
  }
  return que.remove()
}
console.log(playGames(['小刘', '李四', '王五', '李华', '小华', '张三'], 5)) // 最后还剩:小刘