Skip to content

Instantly share code, notes, and snippets.

@theabbie
Last active April 5, 2021 03:40
Show Gist options
  • Save theabbie/bd0547fb070a3888474768ca5baab2af to your computer and use it in GitHub Desktop.
Save theabbie/bd0547fb070a3888474768ca5baab2af to your computer and use it in GitHub Desktop.
Banker’s Algorithm
#include <stdio.h>
#define MAX 20
typedef struct {
int id;
int done;
int claims[MAX];
int allocations[MAX];
int needs[MAX];
} Process;
int main() {
int np,nr,flag;
Process ps[MAX];
int Resources[MAX];
int Available[MAX];
int safe_sequence[MAX];
printf("Number of processes?\n");
scanf("%d",&np);
printf("Number of Resources?\n");
scanf("%d",&nr);
printf("Claim Matrix:\n");
for (int i = 0; i < np; i++) {
ps[i].id = i+1;
ps[i].done = 0;
for (int j = 0; j < nr; j++) {
scanf("%d",&ps[i].claims[j]);
}
}
printf("Allocation Matrix:\n");
for (int i = 0; i < np; i++) {
for (int j = 0; j < nr; j++) {
scanf("%d",&ps[i].allocations[j]);
ps[i].needs[j] = ps[i].claims[j] - ps[i].allocations[j];
}
}
printf("Resource Vector:\n");
for (int i = 0; i < nr; i++) scanf("%d",&Resources[i]);
for (int i = 0; i < nr; i++) {
Available[i] = 0;
for (int j = 0; j < np; j++) Available[i] += ps[j].allocations[i];
Available[i] = Resources[i] - Available[i];
}
printf("\nNeed Matrix:\n");
printf(" ");
for (int j = 0; j < nr; j++) printf("R%d ",j+1);
printf("\n");
for (int i = 0; i < np; i++) {
printf("P%d ",i+1);
for (int j = 0; j < nr; j++) printf("%2d ",ps[i].needs[j]);
printf("\n");
}
printf("\nResource Vector: ");
for (int j = 0; j < nr; j++) printf("%d ",Resources[j]);
printf("\n");
printf("Available Vector: ");
for (int j = 0; j < nr; j++) printf("%d ",Available[j]);
printf("\n");
for (int i = 0; i < np; i++) {
for (int j = 0; j < np; j++) {
if (ps[j].done) continue;
flag = 1;
for (int k = 0; k < nr; k++) {
if (ps[j].needs[k] > Available[k]) {
flag = 0;
break;
}
}
if (flag) {
for (int k = 0; k < nr; k++) {
Available[k] += ps[j].allocations[k];
ps[j].needs[k] = 0;
safe_sequence[i] = ps[j].id;
}
ps[j].done = 1;
break;
}
}
}
printf("\nClaim Matrix:\n");
printf(" ");
for (int j = 0; j < nr; j++) printf("R%d ",j+1);
printf("\n");
for (int i = 0; i < np; i++) {
printf("P%d ",i+1);
for (int j = 0; j < nr; j++) printf("%2d ",ps[i].claims[j]);
printf("\n");
}
printf("\nAllocation Matrix:\n");
printf(" ");
for (int j = 0; j < nr; j++) printf("R%d ",j+1);
printf("\n");
for (int i = 0; i < np; i++) {
printf("P%d ",i+1);
for (int j = 0; j < nr; j++) printf("%2d ",ps[i].allocations[j]);
printf("\n");
}
printf("\nSafe Sequence: ");
for (int i = 0; i < np; i++) printf("P%d ",safe_sequence[i]);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment