JavaScript實現迴圈佇列與約瑟夫環問題的解決
阿新 • • 發佈:2018-12-13
function MyCircularQueue(){ var items = []; //向佇列插入元素 this.enQueue = function(value){ return items.push(value); } //刪除元素 this.deQueue = function(){ return items.shift(); } //檢視隊首元素 this.front = function(){ return items[0]; } //檢視佇列 this.print = function(){ return items.toString(); } //檢視佇列長度 this.size = function(){ return items.length; } //檢視佇列是否為空 this.isEmpty = function(){ return items.length == 0; } } /*約瑟夫環問題 * 一群孩子圍成一圈,每次傳遞 n 個數, * 停下來時手裡拿花的孩子被淘汰,直到隊伍中只剩下一個孩子 * 即勝利者。 */ /*引數 *nameList 參與遊戲的人數 *n 制定的傳遞次數 */ function getLastPerson(nameList, n){ var queue = new MyCircularQueue(); //將名單存入佇列 for(var i = 0; i < nameList.length; i++){ queue.enQueue(nameList[i]); } var loser = ''; while(queue.size() > 1){ for(var i = 0; i < n; i++){ queue.enQueue(queue.deQueue()); } loser = queue.deQueue(); console.log('剩餘人數' + queue.print() + ' ' + '被淘汰的人為:' + loser); } return queue.deQueue(); } var nameList = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; var winner = getLastPerson(nameList, 6); console.log('獲勝者:' + winner);