Here’s a task I had the other day. While working on it I thought, “this might make a nice interview question.”

You have an m × n matrix of data, for example:

1 2 3 4 
5 6 7 8 

It has been stored into a 1-D array in column-major order:

1 5 2 6 3 7 4 8

Write a function that takes this array and returns a new array with the same data in row-major order:

1 2 3 4 5 6 7 8

The code that I ended up with:

public double[] ToRowMajor(double[] colMajor1D, int nrow)
{
    if (colMajor1D == null)
    {
        throw new ArgumentNullException(nameof(colMajor1D));
    }

    var len = colMajor1D.Length;

    if (len <= 0)
    {
        throw new ArgumentException(
            @"Data must not be empty",
            nameof(colMajor1D));
    }
    if (nrow < 1)
    {
        throw new ArgumentOutOfRangeException(
            nameof(nrow), 
            @"Must have a positive number of rows");
    }
    if (len % nrow != 0)
    {
        throw new ArgumentException(
            $@"Data should contain exactly {nrow} rows",
            nameof(nrow));
    }

    var ncol = len / nrow;
    var rowMajor1D = new double[len];

    int offset = 0;
    for (int i = 0; i < nrow; i++)
    {
        for (int j = 0; j < ncol; j++)
        {
            rowMajor1D[offset++] = colMajor1D[(j * nrow) + i];
        }
    }

    return rowMajor1D;
}