Untitled
unknown
c_cpp
5 months ago
2.7 kB
6
Indexable
#include <iostream> #include <vector> using namespace std; // Number of processes and resources const int P = 5; const int R = 3; // Class representing the Banker's Algorithm class BankersAlgorithm { private: vector<int> processes; vector<int> available; vector<vector<int>> maxm; vector<vector<int>> allocation; vector<vector<int>> need; public: BankersAlgorithm(vector<int> procs, vector<int> avail, vector<vector<int>> maxMatrix, vector<vector<int>> allocMatrix) : processes(procs), available(avail), maxm(maxMatrix), allocation(allocMatrix) { need.resize(P, vector<int>(R, 0)); calculateNeed(); } // Function to calculate the Need matrix void calculateNeed() { for (int i = 0; i < P; i++) { for (int j = 0; j < R; j++) { need[i][j] = maxm[i][j] - allocation[i][j]; } } } // Function to check if the system is in a safe state bool isSafe() { vector<bool> finish(P, false); vector<int> work = available; vector<int> safeSeq; int count = 0; while (count < P) { bool found = false; for (int i = 0; i < P; i++) { if (!finish[i]) { bool canAllocate = true; for (int j = 0; j < R; j++) { if (need[i][j] > work[j]) { canAllocate = false; break; } } if (canAllocate) { for (int k = 0; k < R; k++) { work[k] += allocation[i][k]; } safeSeq.push_back(processes[i]); finish[i] = true; found = true; count++; } } } if (!found) { cout << "System is not in a safe state" << endl; return false; } } cout << "System is in a safe state.\nSafe sequence is: "; for (int i : safeSeq) { cout << i << " "; } cout << endl; return true; } }; int main() { vector<int> processes = {0, 1, 2, 3, 4}; vector<int> avail = {3, 3, 2}; vector<vector<int>> maxm = { {7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}}; vector<vector<int>> allot = { {0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2}}; BankersAlgorithm banker(processes, avail, maxm, allot); banker.isSafe(); return 0; }
Editor is loading...
Leave a Comment