-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBanker.java
111 lines (93 loc) · 3.23 KB
/
Banker.java
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package spos;
import java.util.*;
public class Banker {
public static void main(String[] args)
{
int avail[] = {3,1,1,2};
int max[][] = {{3,3,2,2},
{1,1,3,4},
{1,3,5,0}};
int allot[][] = {
{1,2,2,1},
{1,0,3,3},
{1,2,1,0}};
isSafe( avail, max, allot);
}
static int P = 3;
static int R = 4;
static void calculateNeed(int need[][], int max[][], int allot[][])
{
for (int i = 0 ; i < P ; i++)
for (int j = 0 ; j < R ; j++)
need[i][j] = max[i][j] - allot[i][j];
}
static boolean isSafe( int avail[], int max[][],
int allot[][])
{
int [][]need = new int[P][R];
calculateNeed(need, max, allot);
boolean []finish = new boolean[P];
int []safeSeq = new int[P];
int []work = new int[R];
for (int i = 0; i < R ; i++)
work[i] = avail[i];
int count = 0;
while (count < P)
{
boolean found = false;
for (int p = 0; p < P; p++)
{
if (finish[p] == false)
{
int j;
for (j = 0; j < R; j++)
if (need[p][j] > work[j])
break;
if (j == R)
{
for (int k = 0 ; k < R ; k++)
work[k] += allot[p][k];
safeSeq[count++] = p;
finish[p] = true;
found = true;
}
}
}
System.out.println("availble matrix: ");
for(int i=0;i<avail.length;i++) {
System.out.print(avail[i]+" ");
}
System.out.println("\n\nmax matrix: ");
for(int i=0;i<P;i++) {
for(int j=0;j<R;j++) {
System.out.print(max[i][j]+ " ");
}
System.out.println();
}
System.out.println("\nneed matrix: ");
for(int i=0;i<P;i++) {
for(int j=0;j<R;j++) {
System.out.print(need[i][j]+ " ");
}
System.out.println();
}
System.out.println("\nallocation matrix: ");
for(int i=0;i<P;i++) {
for(int j=0;j<R;j++) {
System.out.print(allot[i][j]+ " ");
}
System.out.println();
}
if (found == false)
{
System.out.print("\nSystem is not in safe state");
return false;
}
}
System.out.print("System is in safe state.\nSafe"
+" sequence is: ");
for (int i = 0; i < P ; i++)
System.out.print(safeSeq[i] + " ");
return true;
}
}