OneCompiler

os27

118

Q1)
#include <stdio.h>
#include <stdlib.h>

#define MAX_REQUESTS 1000

// Function to sort the disk request string in ascending order
void sortRequests(int *requests, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (requests[j] > requests[j + 1]) {
int temp = requests[j];
requests[j] = requests[j + 1];
requests[j + 1] = temp;
}
}
}
}

// Function to find the index of the head position in the sorted request array
int findHeadIndex(int *requests, int n, int head) {
int index = -1;
for (int i = 0; i < n; i++) {
if (requests[i] >= head) {
index = i;
break;
}
}
return index;
}

// Function to simulate LOOK algorithm
int look(int *requests, int n, int head, int direction) {
// Sort the requests
sortRequests(requests, n);

// Find the index of the head position in the sorted request array
int headIndex = findHeadIndex(requests, n, head);

// Initialize total head movements
int totalHeadMovements = 0;

// If headIndex is -1, it means all requests are before the head, change direction
if (headIndex == -1) {
    direction = -direction;
    headIndex = 0;
}

// Iterate over the requests in the given direction
for (int i = headIndex; i < n && i >= 0; i += direction) {
    printf("%d ", requests[i]);
    totalHeadMovements += abs(requests[i] - head);
    head = requests[i];
}

return totalHeadMovements;

}

int main() {
int n;
printf("Enter the total number of disk blocks: ");
scanf("%d", &n);

int *requests = (int *)malloc(n * sizeof(int));
if (requests == NULL) {
    printf("Memory allocation failed\n");
    return 1;
}

printf("Enter the disk request string:\n");
for (int i = 0; i < n; i++) {
    scanf("%d", &requests[i]);
}

int head, direction;
printf("Enter the current head position: ");
scanf("%d", &head);
printf("Enter the direction (1 for right, -1 for left): ");
scanf("%d", &direction);

printf("The list of requests served in LOOK order:\n");
int totalHeadMovements = look(requests, n, head, direction);
printf("\nTotal number of head movements: %d\n", totalHeadMovements);

free(requests);
return 0;

}
Q2)
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define ARRAY_SIZE 1000

int main(int argc, char **argv) {
int rank, size;
int array[ARRAY_SIZE];
int min, local_min;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

// Seed random number generator
srand(rank);

// Generate random numbers for each process
for (int i = 0; i < ARRAY_SIZE; i++) {
    array[i] = rand();
}

// Find local minimum
local_min = array[0];
for (int i = 1; i < ARRAY_SIZE; i++) {
    if (array[i] < local_min) {
        local_min = array[i];
    }
}

// Reduce local_min values to find the global minimum
MPI_Reduce(&local_min, &min, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);

if (rank == 0) {
    printf("The minimum number is: %d\n", min);
}

MPI_Finalize();

return 0;

}