Last active
August 29, 2015 14:20
-
-
Save monochromer/f7ead2f1d52fb2463079 to your computer and use it in GitHub Desktop.
Реализация структуры "очередь"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Очередь | |
* @constructor | |
*/ | |
function Queue () { | |
/** | |
* Приватная переменная для хранения элементов очереди | |
*/ | |
var items = []; | |
/** | |
* Возвращает количество элементов очереди | |
* @return {number} число элементов в очереди | |
*/ | |
this.size = function () { | |
return items.length; | |
}; | |
/** | |
* Добавление элемента | |
* @param {object} element - добавляемый элемент. | |
*/ | |
this.enqueue = function (element) { | |
items.push(element); | |
}; | |
/** | |
* Удаление элемента из начала очереди | |
* @return {object} - удаляемый элемент. | |
*/ | |
this.dequeue = function () { | |
return items.shift(); | |
}; | |
/** | |
* Возвращает элемент из начала очереди | |
* @return {object} - Первый элемент очереди. | |
*/ | |
this.front = function () { | |
return items[0]; | |
}; | |
/** | |
* Проверка очереди на отстутсвие элементов | |
* @return {boolean} true, если очередь пуста. | |
*/ | |
this.isEmpty = function () { | |
return items.length === 0; | |
}; | |
} | |
function PriorityQueue() { | |
var items = []; | |
function QueueElement (element, priority) { | |
this.element = element; | |
this.priority = priority; | |
} | |
this.enqueue = function (element, priority) { | |
var queueElement = new QueueElement(element, priority); | |
if ( this.isEmpty() ) { | |
items.push(queueElement); | |
} else { | |
var added = false; | |
for (var i = 0; i < items.length; i++ ) { | |
if ( queueElement.priority < items[i].priority ) { | |
items.splice(i, 0, queueElement); | |
added = true; | |
break; | |
} | |
} | |
if (!added) { | |
items.push(queueElement); | |
} | |
} | |
}; | |
//other methods - same as default Queue implementation | |
} | |
// hotPotato game example | |
function hotPotato (nameList, num) { | |
var queue = new Queue(); | |
for ( var i = 0; i < nameList.length; i++ ) { | |
queue.enqueue(nameList[i]); | |
} | |
var eliminated = ''; | |
while ( queue.size() > 1 ) { | |
for (var i = 0; i < num; i++) { | |
queue.enqueue(queue.dequeue()); | |
} | |
eliminated = queue.dequeue(); | |
console.log(eliminated + ' was eliminated from the Hot Potato game.'); | |
} | |
return queue.dequeue(); | |
} | |
var names = ['John','Jack','Camila','Ingrid','Carl']; | |
var winner = hotPotato(names, 5); | |
console.log('The winner is: ' + winner); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment