2022-19 in js
This commit is contained in:
parent
ece85a2e99
commit
3430a7074b
11 changed files with 358 additions and 32 deletions
39
2022/19-Not-Enough-Minerals/priority_queue.js
Normal file
39
2022/19-Not-Enough-Minerals/priority_queue.js
Normal file
|
@ -0,0 +1,39 @@
|
|||
export class QElement {
|
||||
constructor(element, priority) {
|
||||
this.element = element;
|
||||
this.priority = priority;
|
||||
}
|
||||
}
|
||||
|
||||
export class PriorityQueue {
|
||||
constructor(elt) {
|
||||
this.items = [];
|
||||
if (elt !== undefined) {
|
||||
this.enqueue(elt, 0);
|
||||
}
|
||||
}
|
||||
|
||||
enqueue(element, priority) {
|
||||
let qElement = new QElement(element, priority);
|
||||
|
||||
for (let i = 0; i < this.items.length; ++i) {
|
||||
if (this.items[i].priority > qElement.priority) {
|
||||
this.items.splice(i, 0, qElement);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.items.push(qElement);
|
||||
}
|
||||
dequeue() {
|
||||
return this.items.pop(); // pop highest priority, use shift() for lower priority
|
||||
}
|
||||
front() {
|
||||
return this.items[0];
|
||||
}
|
||||
rear() {
|
||||
return this.items[this.items.length - 1];
|
||||
}
|
||||
isEmpty() {
|
||||
return this.items.length === 0;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue