#include <mpi.h> // Include the MPI library for communication
#include <stdio.h> // For input and output
#include <stdlib.h> // For random number generation
int main(int argc, char **argv) {
int rank, size; // Rank of the current process and total number of processes
char report[50]; // Buffer for the treasure report
MPI_Status status; // Variable to hold the status of communication
MPI_Init(&argc, &argv); // Initialize the MPI environment
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the rank of the current process
MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the total number of processes
if (rank == 0) {
// Process 0: John Silver
printf("John Silver is waiting for reports from %d groups of pirates...\n", size
- 1);
for (int i = 1; i < size; i++) {
// Receive reports from all other processes
MPI_Recv(report, 50, MPI_CHAR, i, 0, MPI_COMM_WORLD, &status);
printf("Report from group %d: %s\n", i
, report
); }
printf("All reports received. John Silver can now plan his next move.\n");
} else {
// Other processes: Pirate groups
srand(rank
); // Seed the random number generator with the process rank int found_treasure
= rand() % 2; // Randomly decide if treasure is found (0 or 1)
// Create the report
if (found_treasure) {
sprintf(report
, "Found treasure in section %d!", rank
); } else {
sprintf(report
, "No treasure in section %d.", rank
); }
// Send the report to John Silver (process 0)
MPI_Send(report, 50, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
}
MPI_Finalize(); // Clean up the MPI environment
return 0;
}
I2luY2x1ZGUgPG1waS5oPiAgIC8vIEluY2x1ZGUgdGhlIE1QSSBsaWJyYXJ5IGZvciBjb21tdW5pY2F0aW9uCiNpbmNsdWRlIDxzdGRpby5oPiAvLyBGb3IgaW5wdXQgYW5kIG91dHB1dAojaW5jbHVkZSA8c3RkbGliLmg+IC8vIEZvciByYW5kb20gbnVtYmVyIGdlbmVyYXRpb24KCmludCBtYWluKGludCBhcmdjLCBjaGFyICoqYXJndikgewogICAgaW50IHJhbmssIHNpemU7ICAvLyBSYW5rIG9mIHRoZSBjdXJyZW50IHByb2Nlc3MgYW5kIHRvdGFsIG51bWJlciBvZiBwcm9jZXNzZXMKICAgIGNoYXIgcmVwb3J0WzUwXTsgLy8gQnVmZmVyIGZvciB0aG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