OneCompiler

os24

109

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

#define ARRAY_SIZE 1000

int main(int argc, char *argv[]) {
int rank, size;
int array[ARRAY_SIZE];
int sum = 0;

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

srand(time(NULL) + rank);

// Generate random numbers and calculate sum of odd numbers
for (int i = rank; i < ARRAY_SIZE; i += size) {
    array[i] = rand() % 1000;
    if (array[i] % 2 != 0) {
        sum += array[i];
    }
}

// Perform reduction to get the total sum
int totalSum;
MPI_Reduce(&sum, &totalSum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

if (rank == 0) {
    printf("Total sum of odd numbers: %d\n", totalSum);
}

MPI_Finalize();

return 0;

}
Q2)
#include <stdio.h>

#define MAX_PROCESSES 5
#define MAX_RESOURCES 3

int main() {
int allocation[MAX_PROCESSES][MAX_RESOURCES] = {{0, 1, 0}, {2, 0, 0}, {3, 0, 3}, {2, 1, 1}, {0, 0, 2}};
int maximum[MAX_PROCESSES][MAX_RESOURCES] = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}};
int available[MAX_RESOURCES] = {3, 3, 2};
int need[MAX_PROCESSES][MAX_RESOURCES];

// Calculate need matrix
for (int i = 0; i < MAX_PROCESSES; i++) {
    for (int j = 0; j < MAX_RESOURCES; j++) {
        need[i][j] = maximum[i][j] - allocation[i][j];
    }
}

// Display need matrix
printf("Need matrix:\n");
for (int i = 0; i < MAX_PROCESSES; i++) {
    printf("P%d: ", i);
    for (int j = 0; j < MAX_RESOURCES; j++) {
        printf("%d ", need[i][j]);
    }
    printf("\n");
}

// Safety algorithm
int finish[MAX_PROCESSES] = {0};
int work[MAX_RESOURCES];
for (int i = 0; i < MAX_RESOURCES; i++) {
    work[i] = available[i];
}

printf("Safe sequence: ");
for (int k = 0; k < MAX_PROCESSES; k++) {
    for (int i = 0; i < MAX_PROCESSES; i++) {
        if (finish[i] == 0) {
            int flag = 1;
            for (int j = 0; j < MAX_RESOURCES; j++) {
                if (need[i][j] > work[j]) {
                    flag = 0;
                    break;
                }
            }
            if (flag) {
                printf("P%d ", i);
                finish[i] = 1;
                for (int j = 0; j < MAX_RESOURCES; j++) {
                    work[j] += allocation[i][j];
                }
            }
        }
    }
}
printf("\n");

return 0;

}