//Java program for safe sequence of Banker's algorithm.
import java.util.*;
class SafeAlgo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of processes:");
int n=sc.nextInt();
int p[]=new int[n];
int flag[]=new int[n];
System.out.println("Enter number of resource variables");
int m=sc.nextInt();
int max[][]=new int[n][m];
int allo[][]=new int[n][m];
int need[][]=new int[n][m];
int avail[]=new int[m];
for(int x=0;x<n;x++)
{
System.out.println("Enter process number:");
p[x]=sc.nextInt();
flag[x]=0;
for(int y=0;y<m;y++)
{
System.out.println("Max -> P"+p[x]+" ->"+y+" :");
max[x][y]=sc.nextInt();
}
for(int y=0;y<m;y++)
{
System.out.println("Allocation -> P"+p[x]+" ->"+y+" :");
allo[x][y]=sc.nextInt();
need[x][y]=max[x][y]-allo[x][y];
}
}
System.out.println("Enter available resources:");
for(int y=0;y<m;y++)
avail[y]=sc.nextInt();
System.out.println("Process\tMax\tAllocation\tNeed");
for(int x=0;x<n;x++)
{
System.out.print("P"+p[x]+"\t");
for(int y=0;y<m;y++)
System.out.print(max[x][y]+" ");
System.out.print("\t");
for(int y=0;y<m;y++)
System.out.print(allo[x][y]+" ");
System.out.print("\t\t");
for(int y=0;y<m;y++)
System.out.print(need[x][y]+" ");
System.out.println();
}
int count=0;
while(count<=n)
{
for(int x=0;x<n;x++)
{
if(flag[x]==0)
{
int f=0;
for(int y=0;y<m;y++)
{
if(avail[y]<need[x][y])
{
f=1;
break;
}
}
if(f==0)
{
flag[x]=1;
for(int y=0;y<m;y++)
{
avail[y]+=allo[x][y];
}
System.out.println("P"+p[x]);
count++;
}
}
}
}
}
}
Comments
Post a Comment