chit10
#include <iostream>
#include <vector>
using namespace std;
// Function to perform Next Fit memory allocation
void NextFit(vector<int>& blockSize, int m, vector<int>& processSize, int n) {
// Stores block id of the block allocated to a process
vector<int> allocation(n, -1);
int j = 0; // Pointer to traverse blocks
int t = m - 1; // Sets the new end point
// Pick each process and find suitable blocks
for (int i = 0; i < n; i++) {
// Do not start from the beginning each time
while (j < m) {
if (blockSize[j] >= processSize[i]) {
// Allocate block j to process i
allocation[i] = j;
// Reduce available memory in this block
blockSize[j] -= processSize[i];
// Set the new end point
t = (j - 1 + m) % m;
break;
}
if (t == j) {
// Set the new end point if we've cycled through all blocks
t = (j - 1 + m) % m;
// Break the loop after going through all memory blocks
break;
}
// Move to the next block (mod m ensures we wrap around)
j = (j + 1) % m;
}
}
// Print the allocation results
cout << "Process No.\tProcess Size\tBlock No." << endl;
for (int i = 0; i < n; i++) {
cout << "\t" << i + 1 << "\t" << processSize[i] << "\t\t";
if (allocation[i] != -1) {
cout << allocation[i] + 1 << endl; // Adding 1 for 1-based indexing
} else {
cout << "Not Allocated" << endl;
}
}
}
// Driver code
int main() {
int m, n;
// Input the memory block sizes
cout << "Enter the number of memory blocks: ";
cin >> m;
vector<int> blockSize(m);
cout << "Enter memory block sizes (space-separated): ";
for (int i = 0; i < m; i++) {
cin >> blockSize[i];
}
// Input the process sizes
cout << "Enter the number of processes: ";
cin >> n;
vector<int> processSize(n);
cout << "Enter process sizes (space-separated): ";
for (int i = 0; i < n; i++) {
cin >> processSize[i];
}
// Call the NextFit function to allocate memory
NextFit(blockSize, m, processSize, n);
return 0;
}