-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment4.cpp
More file actions
95 lines (82 loc) · 2.66 KB
/
Assignment4.cpp
File metadata and controls
95 lines (82 loc) · 2.66 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
85
86
87
88
89
90
91
92
93
94
95
/*
Title: Banker's Algorithm (Deadlock Avoidance)
Class: SY-A
Roll No.: 41
Description: Implements the Banker's algorithm to determine if the system is in a safe state.
Time Complexity: O(n^2 * m)
Space Complexity: O(n * m)
*/
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cout << "Enter the number of processes: ";
cin >> n;
cout << "Enter the number of resource types: ";
cin >> m;
vector<vector<int>> alloc(n, vector<int>(m)); // Allocation matrix
vector<vector<int>> maxm(n, vector<int>(m)); // Maximum matrix
vector<vector<int>> need(n, vector<int>(m)); // Need matrix
vector<int> avail(m); // Available resources
vector<int> finish(n, 0); // Finished processes
vector<int> safeSeq(n); // Safe sequence
// Input Allocation matrix
cout << "\nEnter Allocation Matrix (" << n << " x " << m << "):\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> alloc[i][j];
}
}
// Input Maximum Requirement matrix
cout << "\nEnter Maximum Requirement Matrix (" << n << " x " << m << "):\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> maxm[i][j];
}
}
// Input Available Resources
cout << "\nEnter Available Resources (" << m << "):\n";
for (int i = 0; i < m; i++) {
cin >> avail[i];
}
// Calculate Need matrix = Max - Alloc
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
need[i][j] = maxm[i][j] - alloc[i][j];
}
}
int count = 0;
while (count < n) {
bool found = false;
for (int i = 0; i < n; i++) {
if (finish[i] == 0) { // If process not finished
int j;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]) {
break;
}
}
if (j == m) { // All resources available for this process
for (int k = 0; k < m; k++) {
avail[k] += alloc[i][k]; // Release resources
}
safeSeq[count++] = i;
finish[i] = 1;
found = true;
}
}
}
if (!found) {
cout << "\nSystem is in UNSAFE state.\n";
return 0;
}
}
// Print safe sequence
cout << "\nSystem is in SAFE state.\nSafe sequence is: ";
for (int i = 0; i < n; i++) {
cout << "P" << safeSeq[i] << " ";
}
cout << "\n";
return 0;
}