Skip to content

Instantly share code, notes, and snippets.

@roychowdhuryrohit-dev
Created October 11, 2017 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roychowdhuryrohit-dev/4ffcc31299c9d4ed8e6b40e32de68659 to your computer and use it in GitHub Desktop.
Save roychowdhuryrohit-dev/4ffcc31299c9d4ed8e6b40e32de68659 to your computer and use it in GitHub Desktop.
#include <stdio.h>
void sort(int pid[], int at[], int bt[], int n) {
int temp, i, j, flag;
for(i = 1;i<n;i++) {
flag = 1;
for(j = 0;j<(n-i);j++) {
if(at[j]>at[j + 1]) {
temp = pid[j];
pid[j] = pid[j + 1];
pid[j + 1] = temp;
temp = at[j];
at[j] = at[j + 1];
at[j + 1] = temp;
temp = bt[j];
bt[j] = bt[j + 1];
bt[j + 1] = temp;
flag = 0;
}
}
if(flag) {
break;
}
}
}
void display(int pid[], int at[], int bt[], int ct[], int tat[], int wt[], int n) {
int i;
float avg_tat, avg_wt;
puts("\nPID\tAT\tBT\tCT\tTAT\tWT");
for(i = 0;i<n;i++) {
printf("%d\t%d\t%d\t%d\t%d\t%d\n", pid[i], at[i], bt[i], ct[i], tat[i], wt[i]);
avg_tat += tat[i];
avg_wt += wt[i];
}
printf("Average waiting time - %.2f\n", avg_wt/n);
printf("Average turn around time - %.2f", avg_tat/n);
}
void calc(int pid[], int at[], int bt[], int quantum, int n) {
int cur_pindex = 0, i, bt_copy[n], elap, queue[50], front = -1, rear = -1;
int ct[n], tat[n], wt[n];
sort(pid, at, bt, n);
for(i = 0;i<n;bt_copy[i] = bt[i], i++);
elap = at[cur_pindex];
i = 1;
printf("Gantt chart - ");
do {
printf("%d, ", pid[cur_pindex]);
if(bt_copy[cur_pindex]>quantum) {
elap += quantum;
bt_copy[cur_pindex] -= quantum;
}
else {
elap += bt_copy[cur_pindex];
bt_copy[cur_pindex] = 0;
ct[cur_pindex] = elap;
tat[cur_pindex] = ct[cur_pindex] - at[cur_pindex];
wt[cur_pindex] = tat[cur_pindex] - bt[cur_pindex];
}
for(;at[i] <= elap && i<n;i++) {
queue[++rear] = i;
}
if(bt_copy[cur_pindex] != 0) {
queue[++rear] = cur_pindex;
}
cur_pindex = queue[++front];
}
while(front <= rear);
display(pid, at, bt, ct, tat, wt, n);
}
int main() {
int at[] = {5, 4, 3, 1, 2, 6};
int bt[] = {5, 6, 7, 9, 2, 3};
int pid[] = {1, 2, 3, 4, 5, 6};
int quantum = 3, n = 6;
calc(pid, at, bt, quantum, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment