OS Memory Allocation Assignment
Name: Rathod Kavya
Roll No: 2023IMG042
#include <iostream>
#include <vector>
using namespace std;
class RathodKavyaAllocator {
vector<int> memory;
int size;
public:
RathodKavyaAllocator(int n) {
memory = vector<int>(n, 0);
size = n;
}
int allocate(int n, int mID) {
for (int i = 0; i <= size - n; i++) {
bool can_allocate = true;
for (int j = i; j < i + n; j++) {
if (memory[j] != 0) {
can_allocate = false;
break;
}
}
if (can_allocate) {
for (int j = i; j < i + n; j++) {
memory[j] = mID;
}
return i;
}
}
return -1;
}
int free(int mID) {
int count = 0;
for (int i = 0; i < size; i++) {
if (memory[i] == mID) {
memory[i] = 0;
count++;
}
}
return count;
}
};
void firstFitRK(vector<int> blocks, vector<int> processes) {
vector<int> allocation([Link](), -1);
for (int i = 0; i < [Link](); i++) {
for (int j = 0; j < [Link](); j++) {
if (blocks[j] >= processes[i]) {
allocation[i] = j;
blocks[j] -= processes[i];
break;
}
}
}
cout << "\nStrategy Used: First Fit\n";
cout << "Process No.\tProcess Size\tBlock No.\n";
for (int i = 0; i < [Link](); i++) {
cout << i + 1 << "\t\t" << processes[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1 << endl;
else
cout << "Not Allocated\n";
}
}
void bestFitRK(vector<int> blocks, vector<int> processes) {
vector<int> allocation([Link](), -1);
for (int i = 0; i < [Link](); i++) {
int bestIdx = -1;
for (int j = 0; j < [Link](); j++) {
if (blocks[j] >= processes[i]) {
if (bestIdx == -1 || blocks[j] < blocks[bestIdx]) {
bestIdx = j;
}
}
}
if (bestIdx != -1) {
allocation[i] = bestIdx;
blocks[bestIdx] -= processes[i];
}
}
cout << "\nStrategy Used: Best Fit\n";
cout << "Process No.\tProcess Size\tBlock No.\n";
for (int i = 0; i < [Link](); i++) {
cout << i + 1 << "\t\t" << processes[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1 << endl;
else
cout << "Not Allocated\n";
}
}
int main() {
int n, m;
cout << "Enter number of memory blocks: ";
cin >> n;
vector<int> blocks(n);
cout << "Enter sizes of memory blocks: ";
for (int i = 0; i < n; i++)
cin >> blocks[i];
cout << "Enter number of processes: ";
cin >> m;
vector<int> processes(m);
cout << "Enter sizes of processes: ";
for (int i = 0; i < m; i++)
cin >> processes[i];
firstFitRK(blocks, processes);
bestFitRK(blocks, processes);
return 0;
}