JavaScript隊列結構——擊鼓傳花遊戲

JavaScript隊列結構——擊鼓傳花遊戲

//隊列類
function Queue(){
	this.items = []
	//將元素添加到隊列中
	Queue.prototype.enqueue = function(item){
		this.items.push(item)
	}
	//從隊列中刪除前端元素
	Queue.prototype.dequeue = function(){
		return this.items.shift()
	}
	//查看前端元素(不改變原隊列)
	Queue.prototype.front = function(){
		return this.items[0]
	}
	//查看隊列是否爲空
	Queue.prototype.isEmpty = function(){
		return this.items.length == 0
	}
	//查看隊列中元素個數
	Queue.prototype.size = function(){
		return this.items.length
	}
	//toString方法
	Queue.prototype.toString = function(){
		return this.items.join(' ')
	}
}

/* 
擊鼓傳花遊戲,玩家按順序從1開始數數,數到指定的num時出局
剩下的玩家接着重新從1開始數數
最後剩下的玩家獲勝
*/
function passGame(players , num){
	//創建隊列對象
	const queue = new Queue()
	//將所有玩家添加進隊列
	players.forEach(item => {
		queue.enqueue(item)
	})
	//判斷剩餘玩家數量,剩餘數量爲1時結束遊戲
	//最後剩下的玩家爲獲勝者
	while(queue.items.length > 1){
		//下標從0開始,每輪循環num-1次
		//已經數過數並且數的數不是num的玩家,從隊列首端移到尾端
		for (let i = 0; i < num - 1; i++){
			queue.enqueue(queue.dequeue())
		}
		//循環結束後,淘汰數到num的玩家
		queue.dequeue()
	}
	//返回結果
	const winner = queue.front()
	console.log('獲勝者爲:' + winner)
	return winner
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章