C program to implement SCAN algorithm

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

#include <stdio.h>
#include <math.h>

void scan(int head, int Q[], int n, int tracks, int Di) {
int scount = 0;

// Sorting the queue of requests
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (Q[j] > Q[j + 1]) {
int temp = Q[j];
Q[j] = Q[j + 1];
Q[j + 1] = temp;
}
}
}

int index = 0;
for (int i = 0; i < n; i++) {
if (head < Q[i]) {
index = i;
break;
}
}

if (Di == 1) {
for (int i = index; i < n; i++) {
scount += abs(head - Q[i]);
head = Q[i];
}
// Edge case handling: when the head is at the end of tracks
if (index != 0)
scount += abs(tracks - Q[n - 1] - 1);
head = tracks - 1;
for (int i = index - 1; i >= 0; i--) {
scount += abs(head - Q[i]);
head = Q[i];
}
} else {
for (int i = index - 1; i >= 0; i--) {
scount += abs(head - Q[i]);
head = Q[i];
}
// Edge case handling: when the head is at the beginning of tracks
if (index != n)
scount += abs(Q[0] - 0);
head = 0;
for (int i = index; i < n; i++) {
scount += abs(head - Q[i]);
head = Q[i];
}
}
printf("%d", scount);
}

int main() {
int head, n, tracks, Di;
scanf("%d", &head);
printf("0/1");
scanf("%d", &Di);
printf("no of tracks");
scanf("%d", &tracks);
printf("no of q element");
scanf("%d", &n);
int Q[n];
printf("enter q");
for (int i = 0; i < n; i++) {
scanf("%d", &Q[i]);
}
scan(head, Q, n, tracks, Di);
return 0;
}

KaiserImapact
Автор

wrong code I think, as the same values that have been counted in one direction can also be counted in the opposite direction, it can be solved it you declare the req as a structure and lock integer as an attribute, if its the first direction then set the lock as 1 and consider it only if lock==0(initialised as zero).

jamesns
visit shbcf.ru