RoundRobin Using Linked List. Finish Time Calculation Issue - c

we are trying to achieve round robin algorithm using linked list.
But My logic has some errors.
When I try to run it for 3 process then the first process values are wrong and sometimes right for the other below processes.
Please Help me.
I tried Searching for logics
Code Link: https://pastebin.com/FkbtUEaQ
#include<stdio.h>
struct process
{
char na[20];
int at, bt, ft, tat, rem;
//float ntat;
} Q[5], temp;
void roundRobin()
{
int rr[20], q, x, k;
int f, r, n, i, j, tt = 0, qt, t, flag, wt = 0;
float awt = 0, antat = 0, atat = 0;
printf("Enter the no. of jobs:");
scanf("%d", &n);
for (r = 0; r < n; r++)// aceppting arrival; and burst time
{
printf("Enter process name,arrival time and burst time:\n");
scanf("%s%d%d", Q[r].na, &Q[r].at, &Q[r].bt);
}
printf("Enter quantum:\n");
scanf("%d", &qt);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (Q[i].at < Q[j].at) {
temp = Q[i];
Q[i] = Q[j];
Q[j] = temp;
}
}
}
for (i = 0; i < n; i++)
{
Q[i].rem = Q[i].bt;
Q[i].ft = 0;
}
tt = 0;
q = 0;
rr[q] = 0;
do
{
for (j = 0; j < n; j++)
if (tt >= Q[j].at)
{
x = 0;
for (k = 0; k <= q; k++)
if (rr[k] == j)
x++;
if (x == 0)
{
q++;
rr[q] = j;
}
}
if (q == 0)
i = 0;
if (Q[i].rem == 0)
i++;
if (i > q)
i = (i - 1) % q;
if (i <= q)
{
if (Q[i].rem > 0)
{
if (Q[i].rem < qt)
{
tt += Q[i].rem;
Q[i].rem = 0;
} else
{
tt += qt;
Q[i].rem -= qt;
}
Q[i].ft = tt;
}
i++;
}
flag = 0;
for (j = 0; j < n; j++)
if (Q[j].rem > 0)
flag++;
} while (flag != 0);
printf("\n\n\t\tROUND ROBIN ALGORITHM");
printf("\n***************************");
printf("\nprocesses Arrival time burst time finish time tat wt ntat");
for (f = 0; f < n; f++) {
wt = Q[f].ft - Q[f].bt - Q[f].at;
Q[f].tat = Q[f].ft - Q[f].at;
Q[f].ntat = (float) Q[f].tat / Q[f].bt;
antat += Q[f].ntat;
atat += Q[f].tat;
awt += wt;
printf("\n\t%s\t%d\t%d\t%d\t%d\t%d %f", Q[f].na, Q[f].at, Q[f].bt,
Q[f].ft, Q[f].tat, wt, Q[f].ntat);
}
antat /= n;
atat /= n;
awt /= n;
printf("\nAverage tat is %f", atat);
printf("\nAverage normalised tat is %f", antat);
printf("\n average waiting time is %f", awt);
}
void main()
{
roundRobin();
getch();
clrscr();
}
The First Process Gives Wrong Values
processes | ArrivalTime | BurstTime | FinishTime | Tat | WaitTime
a 0 10 60 60 50
b 0 20 30 30 10
c 0 30 50 50 20

In the do while loop you use i to index the rr array with valid indexes 0 to q as well as the Q array with valid indexes 0 to n − 1, of which only the former is correct. So, you have to change every occurrence of Q[i] in this loop to Q[rr[i]].
After that, still the order of the statements
if (Q[rr[i]].rem == 0)
i++;
if (i > q)
i = (i - 1) % q;
is wrong - the test for Q[rr[i]].rem == 0 is to be done each time a new i is chosen, e. g.:
while (Q[rr[i %= q+1]].rem == 0) i++;

Related

Gauss-seidel method algorithm code giving inf numbers in solution

I'm not sure why I'm getting inf values when plugging in a 3 equation answer, another set of eyes on the equation loop would be useful, when I use a single equation the number of iterations is correct but when it's more than that the numbers multiply to inf.
Inputs for the code I used
Enter the Total Number of Equations: 3
Enter Allowed Error: 0.5
Enter the Co-Efficients
Matrix[1][1] = 1
Matrix[1][2] = 2
Matrix[1][3] = 3
Matrix[1][4] = 4
Matrix[2][1] = 2
Matrix[2][2] = 3
Matrix[2][3] = 4
Matrix[2][4] = 5
Matrix[3][1] = 3
Matrix[3][2] = 4
Matrix[3][3] = 5
Matrix[3][4] = 6
#include<stdio.h>
#include<math.h>
int main()
{
int count, t, limit;
float temp, error, a, sum = 0;
float matrix[10][10], y[10], allowed_error;
printf("\nEnter the Total Number of Equations:\t");
scanf("%d", &limit);
printf("Enter Allowed Error:\t");
scanf("%f", &allowed_error);
printf("\nEnter the Co-Efficients\n");
for(count = 1; count <= limit; count++)
{
for(t = 1; t <= limit + 1; t++)
{
printf("Matrix[%d][%d] = ", count, t);
scanf("%f", &matrix[count][t]);
}
}
for(count = 1; count <= limit; count++)
{
y[count] = 0;
}
do
{
a = 0;
for(count = 1; count <= limit; count++)
{
sum = 0;
for(t = 1; t <= limit; t++)
{
if(t != count)
{
sum = sum + matrix[count][t] * y[t];
}
}
temp = (matrix[count][limit + 1] - sum) / matrix[count][count];
error = fabs(y[count] - temp);
if(error > a)
{
a = error;
}
y[count] = temp;
printf("\nY[%d]=\t%f", count, y[count]);
}
printf("\n");
}
while(a >= allowed_error);
printf("\n\nSolution\n\n");
for(count = 1; count <= limit; count++)
{
printf("\nY[%d]:\t%f", count, y[count]);
}
return 0;
}
Your code is correct. The issue is that Gauss-Seidel method does not always converge. The convergence criteria is that the matrix A must be either:
symmetric positive-definite
strictly or irreducibly diagonally dominant
The input matrix you used is neither symmetric, nor diagonally-dominant. Hence, the method fails to converge to a solution.

Shortest Job First Scheduling Algorithm in C issues

I have created a C Program to simulate the Non-Preemptive Shortest Job First Algorithm but it has bugs with certain inputs. The shortest job first algorithm program takes in inputs for the arrival and burst times of the required number of processes and arranges the processes in 2 phases. The first phase involves arranging the program by arrival times and the 2nd phase arranges them by burst times given that their arrival times are lower than the time for the previous process to complete. This is all then compiled in the end and shown.
#include <stdio.h>
// n - total processes
// p - process no. array
// bt - burst time array
// at - arrival time array
// wt - the time taken for the process to start from it's arrival time array
// tat - time spent by process in cpu array
int i, n, j, m, min, sum = 0, x = 1, btTally = 0, p[20], bt[20], at[20], wt[20], tat[20], ta = 0;
float tatTally = 0, wtTally = 0;
//function grabs arrival and burst times of each process and stores it in its respective array
void getInput(){
printf("\nEnter the total number of processes: ");
scanf("%d", & n);
// For Loop for user to input info about the processes
for (i = 0; i < n; i++) {
p[i] = i + 1;
printf("\nEnter the arrival time of process %d: ", p[i]);
scanf(" %d", & at[i]);
printf("\nEnter the burst time of process %d: ", p[i]);
scanf(" %d", & bt[i]);
}
}
//Function arranges processes according to their arrival times
void arrangePhase1(){
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (at[j] > at[i]) {
m = p[j];
p[j] = p[i];
p[i] = m;
m = at[j];
at[j] = at[i];
at[i] = m;
m = bt[j];
bt[j] = bt[i];
bt[i] = m;
}
}
}
}
//Function arranges the processes according to Burst time
void arrangePhase2(){
for (i = 0; i < n; i++) {
btTally = btTally + bt[i];
min = bt[x];
for (j = x; j < n; j++) {
if (bt[j] < min && btTally >= at[j]) {
m = p[x];
p[x] = p[j];
p[j] = m;
m = at[x];
at[x] = at[j];
at[j] = m;
m = bt[x];
bt[x] = bt[j];
bt[j] = m;
}
}
x++;
}
}
//Function calculates the tallies of turnaround time and waiting time
void calcTallies(){
for (i = 0; i < n; i++) {
ta = ta + bt[i];
tat[i] = ta - at[i];
tatTally = tatTally + tat[i];
}
wt[0] = 0;
for (i = 1; i < n; i++) {
sum = sum + bt[i - 1];
wt[i] = sum - at[i];
wtTally = wtTally + wt[i];
}
}
//Function displays all of the information about the algorithm running
void showFinal(){
printf("\nProcess\t Arrival Time\t Burst Time\t Waiting Time\t Turnaround Time");
for (i = 0; i < n; i++) {
printf("\n p%d\t %d\t\t %d\t\t %d\t\t %d", p[i], at[i], bt[i], wt[i], tat[i]);
}
printf("\nAverage Waiting Time: %.2f", (wtTally / n));
printf("\nAverage Turn Around Time: %.2f", (tatTally / n));
}
int main() {
getInput();
arrangePhase1();
arrangePhase2();
arrangePhase2();
calcTallies();
showFinal();
return 0;
}
These are the expected results:
These are the results I get with my programme:
Any help would really be appreciated. Thanks!
I ... rearrange your program a bit ...
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int p, at, bt, wt, tat;
} Job;
#define maxN (20)
Job jobs[maxN ];
int n, btTally = 0, sum = 0, ta = 0;
float tatTally = 0, wtTally = 0;
#define TestSize (5)
Job Test[TestSize] = {
{ 1, 2, 1, 0, 0 },
{ 2, 1, 5, 0, 0 },
{ 3, 4, 1, 0, 0 },
{ 4, 0, 6, 0, 0 },
{ 5, 2, 3, 0, 0 }
};
void getInput(){
int i;
printf("\nEnter the total number of processes: ");
scanf("%d", & n);
if (n == 0) {
for (i = 0; i < TestSize; ++i)
jobs[i] = Test[i];
n = TestSize;
return;
}
// For Loop for user to input info about the processes
for (i = 0; i < n; i++) {
jobs[i].p = i + 1;
printf("\nEnter the arrival time of process %d: ", jobs[i].p);
scanf(" %d", & jobs[i].at);
printf("\nEnter the burst time of process %d: ", jobs[i].p);
scanf(" %d", & jobs[i].bt);
}
}
int compareAT (const void * a, const void * b) {
Job *jobA = (Job *)a;
Job *jobB = (Job *)b;
return ( jobA->at - jobB->at );
}
void arrangePhase1(){
qsort (jobs, n, sizeof(Job), compareAT);
}
void Swap(int i, int j) {
Job m = jobs[i];
jobs[i] = jobs[j];
jobs[j] = m;
}
void calcTallies(){
int i;
for (i = 0; i < n; i++) {
ta = ta + jobs[i].bt;
jobs[i].tat = ta - jobs[i].at;
tatTally = tatTally + jobs[i].tat;
}
jobs[0].wt = 0;
for (i = 1; i < n; i++) {
sum = sum + jobs[i - 1].bt;
jobs[i].wt = sum - jobs[i].at;
wtTally = wtTally + jobs[i].wt;
}
}
void showFinal(){
int i;
printf("\nProcess\t Arrival Time\t Burst Time\t Waiting Time\t Turnaround Time");
for (i = 0; i < n; i++) {
printf("\n p%d\t %d\t\t %d\t\t %d\t\t %d", jobs[i].p, jobs[i].at, jobs[i].bt, jobs[i].wt, jobs[i].tat);
}
printf("\nAverage Waiting Time: %.2f", (wtTally / n));
printf("\nAverage Turn Around Time: %.2f", (tatTally / n));
}
void arrangePhase2() {
int i, j, min, x = 1;
for (i = 0; i < n; i++) {
btTally = btTally + jobs[i].bt;
min = jobs[x].bt;
for (j = x; j < n; j++) {
if (jobs[j].bt < min && btTally >= jobs[j].at) {
Swap(x, j);
min = jobs[x].bt;
showFinal();
}
}
x++;
}
}
int main() {
getInput();
arrangePhase1();
showFinal();
arrangePhase2();
// arrangePhase2();
calcTallies();
showFinal();
return 0;
}
And left some test and prints in it.
The main problem is that the min is not updated. Try to add the update to your original program and see if it works. Next is to move the int i,j; to the functions, does it work now? (it wont work without this if you just add the showFinal(); test to your code).
Now the code I made is not the one true truth, it is just an example from someone who hasn't programmed C in decades.
Short code review.
Using globals are bad in C, you easily gets a problem with your loops if you use globals for loop control, here i,j is reused a lot.
You could use structs more, at least for the 3 main values, makes some of the sorting a bit easier. In either case having a Swap function makes the code easier to check and understand.
void SwapInt(int *i, int *j) {
int m = *i;
*i = *j;
*j = m;
}
SwapInt(&at[i], &at[j]); // example of calling swapping
The 2nd call to arrangePhase2(); doesn't do anything.

How to find the highest and the lowest averages using 2D arrays in c programming?

there's a mistake in my code but i can't find where. it must calculate the averages after reading inputs.
it reads all the code and gets all the inputs but when it comes to calculating the average it does nothing. help please
#include <stdlib.h>
#include <stdio.h>
int main() {
int students, modules, m, n, first_student, last_student, l = 0;
float student[100][20], high = 0, low = 20, average[students], average_mark[students];
printf("Please enter the number of students:\n");
scanf("%d", &students);
printf("Please enter the number of modules:\n");
scanf("%d", &modules);
for (m = 0; m < students; ++m) {
for (n = 0; n < modules; n++) {
printf("Please enter the mark of module %d for student number %d,\n", n + 1, m + 1);
scanf("%f", &student[m][n]);
}
}
for (m = 0; m < students; ++m) {
average[m] = 0;
}
for (n = 0; n < modules; n++) {
average[m] += student[m][n];
average_mark[m] = average[m] / modules;
}
printf("student average\n");
for (m = 0; m < students; ++m) {
printf("%d %f\n", m + 1, average_mark[m]);
}
for (m = 0; m < students; ++m) {
if (average_mark[m] < low) {
average_mark[m] = low;
}
else
if (average_mark[m] == low) {
last_student = m + 1;
}
if (average_mark[m] > high) {
average_mark[m] = high;
}
else
if (average_mark[m] == high) {
first_student = m + 1;
}
}
printf("The student who had the highest mark is %d : %f\n", first_student, high);
printf("The student who had the lowest mark is %d : %f\n", last_student, low);
for (m = 0; m < students; ++m) {
if (average_mark[m] == 10 || average_mark[m] > 10) {
l++;
}
}
printf("the number of students having a mark that equals or exceeds the average is %d\n", l);
return 0;
}
There are some other problems in the code but as a start, you may take a peek below.
edit: The next (2nd) problem noted & corrected. I'm leaving you to find & correct the last (3rd) problem.
// either these values need to be predefined
// or you'll need to dynamically allocate
// arrays using malloc
int MAX_STUDENTS = 100;
int MAX_MODULES = 20;
int main() {
int students, modules, m, n, first_student, last_student, l = 0;
float student[MAX_STUDENTS][MAX_MODULES], high = 0, low = 20, average[MAX_STUDENTS], average_mark[MAX_MODULES];
...
...
...
// the 2nd & 3rd for loops needs to be nested as below
for (m = 0; m < students; ++m) { // this was 2nd
average[m] = 0;
for (n = 0; n < modules; n++) { // this was 3rd
average[m] += student[m][n];
}
// you need to move this line out of 3rd loop
average_mark[m] = average[m] / modules;
}
...
...
...
// this is how you find the lowest & highest ranking students
for (m = 0; m < students; ++m) {
if (average_mark[m] < low) {
low = average_mark[m];
last_student = m;
}
if (average_mark[m] > high) {
high = average_mark[m];
first_student = m;
}
}
printf("The student who had the highest mark is %d : %f\n", first_student + 1, high);
printf("The student who had the lowest mark is %d : %f\n", last_student + 1, low);
...
...
...
}

This is a c program to find next greatest number with same digits. But not passing one test case

This is a C program to find the next greater number with the same digits. This program is working for all given test cases except one. When the input is 472, the expected output is 724. But my output is 247. Can anyone please help me to find the error?
logic I tried to solve this is :
Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is 534976, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is Not Possible.
Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For 534976, the right side of 4 contains 976. The smallest digit greater than 4 is 6.
Swap the above found two digits, we get 536974 in above example.
Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get 536479 which is the next greater number for input 534976.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int N, dig[100], i = 0,j, temp, t, s, k, l, min, temp1;
scanf("%d", &N);
while (N > 0) {
dig[i] = N % 10;
i++;
N = N / 10;
}
for (j = 0; j <= i; j++) {
if (dig[j] > dig[j + 1]) {
s = j;
break;
}
}
min = dig[s];
//printf("%d ", min);
for (k = s; k >= 0; k--) {
if (dig[k] <= min) {
min = dig[k];
t = k;
}
}
//printf("%d ", t);
temp = dig[t];
dig[t] = dig[s + 1];
dig[s + 1] = temp;
for (k = 0; k <= s; k++) {
for (l = k + 1; l <= s; l++) {
if (dig[k] < dig[l]) {
temp1 = dig[k];
dig[k] = dig[l];
dig[l] = temp1;
}
}
}
for (k = i - 1; k >= 0; k--) {
printf("%d", dig[k]);
}
}
Your algorithm seems correct, but the loops are incorrect. Some index boundaries are off by one and the comparisons with <= are incorrect. Storing the digits by increasing powers of 10, while more practical is counter-intuitive and complicates the translation of the algorithm into code.
Here is a corrected version, that outputs all greater numbers. You can easily check the output by piping through sort -c to verify order and wc -l to verify that all combinations have been found (there should be at most n! - 1 greater numbers for a number with n digits).
#include <stdio.h>
int main() {
int N, dig[100], i, j, s, t, k, l, temp;
if (scanf("%d", &N) != 1 || N < 0)
return 1;
for (;;) {
for (i = j = 100; N > 0;) {
dig[--i] = N % 10;
N = N / 10;
}
for (s = j - 2; s >= i; s--) {
if (dig[s] < dig[s + 1]) {
break;
}
}
if (s < i) {
/* no greater number with the same digits */
break;
}
t = s + 1;
for (k = t + 1; k < j; k++) {
if (dig[k] < dig[t] && dig[k] > dig[s]) {
t = k;
}
}
temp = dig[t];
dig[t] = dig[s];
dig[s] = temp;
for (k = s + 1; k < j; k++) {
for (l = k + 1; l < j; l++) {
if (dig[k] > dig[l]) {
temp = dig[k];
dig[k] = dig[l];
dig[l] = temp;
}
}
}
N = 0;
for (k = i; k < j; k++) {
N = N * 10 + dig[k];
printf("%d", dig[k]);
}
printf("\n");
}
return 0;
}
Input: 472
Output:
724
742

Calculate matrix determinant with partial pivoting Gauss in C

I'm trying to make a simple console application in C which will calculate the determinant of a Matrix using the Gauss partial pivoting elimination method. The 2 problems that I have are :
- someone told me that there are certain matrix-es that don't work with this method ( mathematically speaking ), after reading articles on google, i could not find what is that special case
- after a lot of tests I found out that my program is not working for some matrix-es, after 2 days of "wasting" time editing and undoing, i could not find the problem.
Any type of improvements are more than welcomed. I'm just starting with C.
#include<stdio.h>
#include<cstdlib>
#include<math.h>
#include<conio.h>
#include<windows.h>
// calculate biggest element on column
int indice_max(int dim, int col, float coloana[20][20]) {
float max = 0;
int indice;
for(int i = 1; i <= dim; i++)
if(fabs(max) < fabs(coloana[i][col])) {
max = coloana[i][col];
indice = i;
}
return indice;
}
// permute 2 lines
void permutare_linie(int linie1, int linie2, int dim, float matrice[20][20]) {
float aux;
for(int i = 1; i <= dim; i++) {
aux = matrice[linie1][i];
matrice[linie1][i] = matrice[linie2][i];
matrice[linie2][i] = aux;
}
}
// print matrix
void afisare_matrice(int dimensiune, float matrice[20][20], int lpiv) {
for(int i = 1; i<= dimensiune; i++) {
for(int j = 1; j <= dimensiune; j++) {
if(i == lpiv)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_GREEN);
else
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE );
printf("%4.2f ", matrice[i][j]);
}
printf("\n");
}
}
void main(void) {
float matrice[20][20];
int dimensiune ;
float rezultat = 1;
float pivot;
int lpiv;
int cpiv;
int optiune;
while(1) {
// MENU
printf("ALEGET OPTIUNEA:\n");
printf("1) Calculate matrix determinant\n");
printf("2) Exit\n");
scanf("%d", &optiune);
if(optiune == 1) {
// Read determinant dimension
printf("Matrix dimension:");
scanf("%d", &dimensiune);
// Read determinant
for(int i = 1; i <= dimensiune; i++)
for(int j = 1; j <= dimensiune; j++) {
printf("M[%d][%d]=", i, j);
scanf("%f", &matrice[i][j]);
}
// pivot initial coords
lpiv = 1;
cpiv = 1;
printf("\n----- Entered Matrix -----\n\n");
afisare_matrice(dimensiune, matrice, 0);
printf("\n");
for(int pas = 1; pas <= dimensiune - 1; pas++) {
if(fabs(matrice[lpiv][cpiv]) > fabs(matrice[indice_max(dimensiune, cpiv, matrice)][cpiv])) {
permutare_linie(lpiv, indice_max(dimensiune, cpiv, matrice), dimensiune, matrice);
rezultat = -(rezultat);
}
pivot = matrice[lpiv][cpiv];
for(int inm = 1; inm <= dimensiune; inm++) {
matrice[lpiv][inm] = matrice[lpiv][inm] / pivot;
}
rezultat *= fabs(pivot);
// transform matrix to a superior triangular
for(int l = lpiv+1; l <= dimensiune; l++)
for(int c=cpiv+1; c <= dimensiune; c++) {
matrice[l][c] -= matrice[l][cpiv] * matrice[lpiv][c] / matrice[lpiv][cpiv];
}
for(int i = lpiv + 1; i <= dimensiune; i++)
matrice[i][cpiv] = 0;
// afisam rezultat / pas
printf("----- Step %d -----\n\n", pas);
afisare_matrice(dimensiune, matrice, lpiv);
printf("\nResult after step %d : %4.2f\n\n", pas, rezultat);
lpiv++;
cpiv++;
}
// final result
rezultat = rezultat * matrice[dimensiune][dimensiune];
printf("----- REZULTAT FINAL -----\n\n");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("Rezultat = %4.2f\nRezultat rotunjit:%4.0f\n\n", rezultat, floorf(rezultat * 100 + 0.5) / 100);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE );
}
else {
exit(0);
}
}
}
Your code does some division:
matrice[lpiv][inm] = matrice[lpiv][inm] / pivot;
If it happens to divide by zero, an error will occur. I guess this will happen for the zero matrix.
It seems that your code is actually trying to invert the matrix, not just calculate the determinant.

Resources