-
Notifications
You must be signed in to change notification settings - Fork 0
/
프린터.js
89 lines (70 loc) · 1.66 KB
/
프린터.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Solution 1
function solution1(priorities, location) {
const _priorities = priorities.slice();
const queue = Array.from({ length: _priorities.length }, (_, index) => index);
const done = [];
while (queue.length > 0) {
const topPriority = Math.max(..._priorities);
const outputPriority = _priorities.shift();
const outputWork = queue.shift();
if (outputPriority === topPriority) {
done.push(outputWork);
} else {
queue.push(outputWork);
_priorities.push(outputPriority);
}
}
const order = done.indexOf(location) + 1;
return order;
}
// Solution 2
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
}
enqueue(newValue) {
const newNode = new Node(newValue);
if (this.head === null) {
this.head = this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
dequeue() {
const value = this.head.value;
this.head = this.head.next;
return value;
}
peek() {
return this.head.value;
}
}
function solution2(priorites, location) {
const _priorites = priorites.slice();
const queue = new Queue();
let count = 0;
for (let i = 0; i < _priorites.length; i++) {
queue.enqueue([_priorites[i], i]);
}
_priorites.sort((a, b) => b - a);
while (true) {
const [currentPriority, _] = queue.peek();
if (currentPriority < _priorites[count]) {
queue.enqueue(queue.dequeue());
} else {
const [_, index] = queue.dequeue();
count += 1;
if (location === index) {
return count;
}
}
}
}