/* 08_comm_split.c - split MPI_COMM_WORLD into "row" and "column" communicators.
 * Processes are laid out in a grid with NCOLS columns. Ranks with the same colour end
 * up in the same new communicator; the key decides their order inside it.
 * Build: mpicc -O2 -o 08_comm_split 08_comm_split.c
 * Run:   mpirun -np 6 ./08_comm_split
 */
#include <stdio.h>
#include <mpi.h>

#define NCOLS 3

int main(int argc, char **argv)
{
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    int row = rank / NCOLS, col = rank % NCOLS;

    MPI_Comm row_comm, col_comm;
    MPI_Comm_split(MPI_COMM_WORLD, row, col, &row_comm);   /* colour = row, key = col */
    MPI_Comm_split(MPI_COMM_WORLD, col, row, &col_comm);   /* colour = col, key = row */

    int row_rank, row_size, row_sum;
    MPI_Comm_rank(row_comm, &row_rank);
    MPI_Comm_size(row_comm, &row_size);
    MPI_Allreduce(&rank, &row_sum, 1, MPI_INT, MPI_SUM, row_comm);   /* only within my row */

    int col_max;
    MPI_Allreduce(&rank, &col_max, 1, MPI_INT, MPI_MAX, col_comm);   /* only within my column */

    printf("world rank %d -> row %d (rank %d of %d, row sum %d), column %d (max %d)\n",
           rank, row, row_rank, row_size, row_sum, col, col_max);

    MPI_Comm_free(&row_comm);
    MPI_Comm_free(&col_comm);
    MPI_Finalize();
    return 0;
}
