/* disk2.c - disk scheduling: C-SCAN, LOOK, C-LOOK (BACSE106 Lab 14) */
#include <stdio.h>

int main(void)
{
    int n, head, size, choice, i, j, total = 0, start;
    int req[50];

    printf("Number of requests: ");
    scanf("%d", &n);
    printf("Request queue: ");
    for (i = 0; i < n; i++) scanf("%d", &req[i]);
    printf("Initial head position: ");
    scanf("%d", &head);
    printf("Disk size (number of cylinders): ");
    scanf("%d", &size);
    printf("1.C-SCAN  2.LOOK  3.C-LOOK (towards higher cylinders)  Choice: ");
    scanf("%d", &choice);

    for (i = 0; i < n; i++)                              /* sort requests */
        for (j = i + 1; j < n; j++)
            if (req[j] < req[i]) { int t = req[i]; req[i] = req[j]; req[j] = t; }

    start = head;
    printf("\nHead movement: %d", head);
    for (i = 0; i < n; i++)                              /* all three first sweep up */
        if (req[i] >= start) { total += req[i] - head; head = req[i]; printf(" -> %d", head); }

    if (choice == 1) {                                   /* C-SCAN: to the end, jump to 0, sweep up */
        total += (size - 1) - head;  printf(" -> %d", size - 1);
        total += size - 1;           printf(" -> 0");     /* return seek counted */
        head = 0;
        for (i = 0; i < n; i++)
            if (req[i] < start) { total += req[i] - head; head = req[i]; printf(" -> %d", head); }
    } else if (choice == 2) {                            /* LOOK: reverse at the last request */
        for (i = n - 1; i >= 0; i--)
            if (req[i] < start) { total += head - req[i]; head = req[i]; printf(" -> %d", head); }
    } else {                                             /* C-LOOK: jump to the lowest request, sweep up */
        for (i = 0; i < n; i++)
            if (req[i] < start) {
                total += (head > req[i]) ? head - req[i] : req[i] - head;
                head = req[i];
                printf(" -> %d", head);
            }
    }
    printf("\nTotal head movement = %d cylinders\n", total);
    return 0;
}
