-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory-reallocation2.js
49 lines (37 loc) · 1003 Bytes
/
memory-reallocation2.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
const memoryReallocation = (input) => {
const banks = input.trim().split(/[\s\t/]+/).map((x) => parseInt(x));
const patterns = {};
let snapshot = banks.join(':');
patterns[snapshot] = {
lastSeen: 0,
alreadySeen: false,
};
while (!(patterns[snapshot] || {}).alreadySeen) {
let blocks = Math.max(...banks);
let currentIndex = banks.findIndex((x) => x === blocks);
if (!patterns[snapshot]) {
patterns[snapshot] = {
lastSeen: 0,
alreadySeen: false,
};
}
banks[currentIndex] = 0;
currentIndex += 1;
while (blocks > 0) {
if (currentIndex === banks.length) {
currentIndex = 0;
}
banks[currentIndex] += 1;
currentIndex += 1;
blocks -= 1;
}
snapshot = banks.join(':');
if (patterns[snapshot]) {
return patterns[snapshot].lastSeen + 1;
}
Object
.keys(patterns)
.forEach((x) => patterns[x].lastSeen += 1);
}
};
module.exports = memoryReallocation;