Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.util.Scanner;
- public class BankersAlgorithm {
- //np = no. of processes \ nr = no. of resources
- private int need[][], allocate[][], max[][];
- private int avail[][], safeSequence[], np, nr;
- private void input() {
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter no. of processes: ");
- np = sc.nextInt(); //no. of processes
- System.out.print("Enter no. of resources: ");
- nr = sc.nextInt(); //no. of resources
- need = new int[np][nr]; //initializing arrays
- max = new int[np][nr];
- allocate = new int[np][nr];
- avail = new int[1][nr];
- safeSequence = new int[np];
- System.out.println("Enter allocation matrix: ");
- for (int i = 0; i < np; i++)
- for (int j = 0; j < nr; j++)
- allocate[i][j] = sc.nextInt(); //allocation matrix
- System.out.println("Enter max. matrix: ");
- for (int i = 0; i < np; i++)
- for (int j = 0; j < nr; j++)
- max[i][j] = sc.nextInt(); //max matrix
- System.out.println("Enter available matrix: ");
- for (int j = 0; j < nr; j++)
- avail[0][j] = sc.nextInt(); //available matrix
- sc.close();
- }
- //calculate the need matrix
- private int[][] calc_need() {
- for (int i = 0; i < np; i++) {
- for (int j = 0; j < nr; j++) { //calculating need matrix
- need[i][j] = max[i][j] - allocate[i][j];
- }
- }
- return need;
- }
- public void isSafe() {
- input(); //collecting data from the user
- calc_need(); //mathmagics here :DD
- //visited array to find the already allocated process
- boolean visited[] = new boolean[np];
- for (int i = 0; i < np; i++) {
- visited[i] = false;
- }
- //work array to store the copy of available resources
- int work[] = new int[nr];
- for (int i = 0; i < nr; i++) {
- work[i] = avail[0][i];
- }
- int count = 0;
- while (count < np) {
- boolean flag = false;
- for (int i = 0; i < np; i++) {
- if (visited[i] == false) {
- int j;
- for (j = 0; j < nr; j++) {
- if (need[i][j] > work[j])
- break;
- }
- if (j == nr) {
- safeSequence[count++] = i;
- visited[i] = true;
- flag = true;
- for (j = 0; j < nr; j++) {
- work[j] = work[j] + allocate[i][j];
- }
- }
- }
- }
- if (flag == false) {
- break;
- }
- }
- if (count < np) {
- System.out.println("The System is UnSafe!");
- } else {
- //System.out.println("The given System is Safe");
- System.out.println("Following is the SAFE Sequence");
- for (int i = 0; i < np; i++) {
- System.out.print("P" + safeSequence[i]);
- if (i != np - 1)
- System.out.print(" -> ");
- }
- }
- }
- public static void main(String[] args) throws IOException {
- new BankersAlgorithm().isSafe();
- }
- }
Add Comment
Please, Sign In to add comment