-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBest-fit.js
More file actions
84 lines (74 loc) · 2.35 KB
/
Best-fit.js
File metadata and controls
84 lines (74 loc) · 2.35 KB
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
class MemoryBlock {
constructor(start, size) {
this.start = start;
this.size = size;
this.allocated = true;
}
}
class MemoryManager {
constructor(totalSize) {
this.totalSize = totalSize;
this.memory = [];
}
systemError(start, size) {
for (let block of this.memory) {
let blockEnd = block.start + block.size;
let newBlockEnd = start + size;
if (!(newBlockEnd <= block.start || start >= blockEnd)) {
return true;
}
}
return false;
}
makeBlock() {
let maxAttempts = 100;
while (maxAttempts-- > 0) {
let size = Math.floor(Math.random() * 80) + 10;
let start = Math.floor(Math.random() * (this.totalSize - size));
if (!this.systemError(start, size)) {
let block = new MemoryBlock(start, size);
this.memory.push(block);
return block;
}
}
return null;
}
threeBlock() {
for (let i = 0; i < 3; i++) {
let block = this.makeBlock();
if (!block) {
console.log("메모리 블록 생성 실패!");
return;
}
}
}
bestFitAllocate(taskSize) {
let subscript = 0;
let minWaste = Infinity;
for (let i = 0; i < this.memory.length; i++) {
let block = this.memory[i];
let waste = block.size - taskSize;
if (waste >= 0 && waste < minWaste) {
minWaste = waste;
subscript = i;
}
}
if (minWaste === Infinity) {
console.log("적절한 블록이 없어 작업을 대기시킵니다.");
return;
}
let selectedBlock = this.memory[subscript];
console.log(`작업 크기 ${taskSize}를 블록 ${subscript} (시작: ${selectedBlock.start}, 크기: ${selectedBlock.size})에 할당합니다.`);
selectedBlock.size = taskSize;
}
printMemory() {
console.log("메모리 블록 목록:");
this.memory.forEach((block, index) => {
console.log(`블록 ${index} - 시작: ${block.start}, 크기: ${block.size}`);
});
}
}
let manager = new MemoryManager(300);
manager.threeBlock();
manager.printMemory();
manager.bestFitAllocate(40);