The first step of the banker's algorithm is to find what each process may still ask for: its need, which is the most it will ever want (Max) minus what it holds now (Allocation).
What to build
Compute the Need matrix, and list the processes whose need fits in what is available right now.
Requirements
- Read the Allocation matrix, the Max matrix and the Available vector, as in the banker's algorithm.
- Print one line
Pi: ...for each process, with itsmneed values. Then printcan run now:followed by the processes (P0,P1, ...) whose need is at most Available in every resource, in order, ornone.
Input
The first line has n and m (1 ≤ n ≤ 10 processes, 1 ≤ m ≤ 5 resource types). Then n lines of Allocation, n lines of Max (each with m numbers), and one line with the m numbers of Available.
Output
n lines Pi: and the m numbers of its need, separated by spaces, then the can run now: line.
Constraints
Max is never below Allocation for any process and resource.
Example
Input:
5 3
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
3 3 2
Output:
P0: 7 4 3
P1: 1 2 2
P2: 6 0 0
P3: 0 1 1
P4: 4 3 1
can run now: P1 P3
Why it works
Need is the part of each process's promise that has not been used yet. A process whose need fits in Available can be given everything it may still ask for, so it is sure to finish; the safety check of the banker's algorithm repeats this test again and again.
Examples
5 3 0 1 0 2 0 0 3 0 2 2 1 1 0 0 2 7 5 3 3 2 2 9 0 2 2 2 2 4 3 3 3 3 2
P0: 7 4 3 P1: 1 2 2 P2: 6 0 0 P3: 0 1 1 P4: 4 3 1 can run now: P1 P3
2 1 1 1 3 3 0
P0: 2 P1: 2 can run now: none
Hints
Hint 1
Need[i][r] = Max[i][r] - Allocation[i][r] for every process i and resource r.
Hint 2
A process can run now if every one of its need values is at most the Available value of the same resource.
Hint 3
Print `none` after "can run now:" when no process qualifies.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int n, m, alloc[10][5], max[10][5], avail[5], need[10][5];
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
for (int r = 0; r < m; r++) scanf("%d", &alloc[i][r]);
for (int i = 0; i < n; i++)
for (int r = 0; r < m; r++) scanf("%d", &max[i][r]);
for (int r = 0; r < m; r++) scanf("%d", &avail[r]);
for (int i = 0; i < n; i++) {
printf("P%d:", i);
for (int r = 0; r < m; r++) {
need[i][r] = max[i][r] - alloc[i][r];
printf(" %d", need[i][r]);
}
printf("\n");
}
int any = 0;
printf("can run now:");
for (int i = 0; i < n; i++) {
int fits = 1;
for (int r = 0; r < m; r++)
if (need[i][r] > avail[r]) fits = 0;
if (fits) {
printf(" P%d", i);
any = 1;
}
}
if (!any) printf(" none");
printf("\n");
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step