bankers algorithm program in java

import java.util.*;
class Bankers
{
int claim[][],alloc[][],av[],need[],p,r,alsum[],sum,temp[][];
int a=0,b=0,c;
boolean flag;
Scanner src = new Scanner(System.in);
Bankers(int p,int r)
{
this.p=p;
this.r=r;
claim=new int[p][r];
alloc=new int[p][r];
av=new int [r];
need=new int [r];
alsum=new int[r];
temp=new int[p][r];
System.out.println("ENTER THE "+r+" VALUES IN AVAILABLE VECTOR");
for(int i=0;i<r;i++)
{
av[i]=src.nextInt();
}
System.out.println("ENTER THE CLAIM MATRIX OF"+p+" X "+r);
for(int i=0;i<p;i++)
for(int j=0;j<r;j++)
claim[i][j]=src.nextInt();
System.out.println("ENTER THE ALLOCATION MATRIX OF "+p+" X "+r);
for(int i=0;i<p;i++)
for(int j=0;j<r;j++)
alloc[i][j]=src.nextInt();
}
public void calNeed()
{
for(int i=0;i<r;i++)
{
for(int j=0;j<p;j++)
{
sum=sum+alloc[j][i];
}
alsum[i]=sum;
sum=0;
}
for(int i=0;i<r;i++)
{
need[i]=av[i]-alsum[i];
System.out.print("Initial Need Vector ");
System.out.print(need[i]);
System.out.println();
System.out.println();
} }
public void checkNeed()
{
for( int i=0;i<p;i++)
for(int j=0;j<r;j++)
{
temp[i][j]=claim[i][j]-alloc[i][j];
} }
public void compareNeed()
{
while(b<p)
{
flag=false;
for(int i=0;i<p;i++)
{
for(int j=0;j<r;j++)
{
if(temp[i][0]==89)
break;
if(temp[i][j]<=need[j])
a++ ;
else break;
}
if(a==r)
{
System.out.println("Process P"+(i+1)+" is Completed");
addtoNeed(i);
temp[i][0]=89;
a=0;
c++;
flag=true;
}
if(flag==true)
break;
}
b++;
}
}
public void addtoNeed(int k)
{
int n=k;
for(int j=0;j<r;j++)
{
need[j]=need[j]+alloc[n][j];
}
if(c==p)
System.out.println("SYSTEM IS IN SAFE STATE");
else
System.out.println("SYSTEM IS NOT IN SAFE STATE");
}
}
class BankerExp1
{
public static void main(String args[])
{
Scanner src = new Scanner(System.in);
System.out.println("ENTER THE NO. OF PROCESS");
int p= src.nextInt();
System.out.println("ENTER THE NO. OF RESOURCES");
int r = src.nextInt();
Bankers obj = new Bankers(p,r);
obj.calNeed();
obj.checkNeed();
obj.compareNeed();
}
}

bankers algorithm program in java OUTPUT:-
ENTER THE NO. OF PROCESS
4
ENTER THE NO. OF RESOURCES
3
ENTER THE 3 VALUES IN AVAILABLE VECTOR
9 3 6
ENTER THE CLAIM MATRIX OF 4 X 3
3 2 2
6 1 3
3 1 4
4 2 2
ENTER THE ALLOCATION MATRIX OF 4 X 3
1 0 0
5 1 1
2 1 1
0 0 2
Initial Need Vector 1
Initial Need Vector 1
Initial Need Vector 2
Process P2 is Completed
Process P1 is Completed
Process P3 is Completed
Process P4 is Completed
SYSTEM IS IN SAFE STATE

Facing difficulties in understanding the program ?

Ask Your Queries in Comment Box

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *