OneCompiler

chit9

1692

#include <iostream>
#include <vector>

using namespace std;

// Function to implement Worst Fit algorithm
void worstFit(vector<int>& blockSize, int m, vector<int>& processSize, int n) {
// Array to store block id of the block allocated to a process
// Initially, no block is assigned to any process
vector<int> allocation(n, -1);

// Loop over each process to find suitable blocks
for (int i = 0; i < n; i++) {
    // Find the worst fit block for the current process
    int worstIdx = -1;
    for (int j = 0; j < m; j++) {
        if (blockSize[j] >= processSize[i]) {
            if (worstIdx == -1) {
                worstIdx = j;
            }
            else if (blockSize[worstIdx] < blockSize[j]) {
                worstIdx = j;
            }
        }
    }

    // If we could find a block for the current process
    if (worstIdx != -1) {
        // Allocate block j to process i
        allocation[i] = worstIdx;

        // Reduce available memory in this block
        blockSize[worstIdx] -= processSize[i];
    }
}

// Display the results
cout << "Process No.\tProcess Size\tBlock no." << endl;
for (int i = 0; i < n; i++) {
    cout << i + 1 << "\t\t" << processSize[i] << "\t\t";
    if (allocation[i] != -1) {
        cout << allocation[i] + 1 << endl;
    } else {
        cout << "Not Allocated" << endl;
    }
}

}

int main() {
// Example input
vector<int> blockSize = {100, 500, 200, 300, 600};
vector<int> processSize = {212, 417, 112, 426};

int m = blockSize.size();
int n = processSize.size();

// Call the worst fit function
worstFit(blockSize, m, processSize, n);

return 0;

}