Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to shuffle the rows of a 2d array in C#

For example, I have 2d array:

int[,] array = new int[3,3] {{1,2,3}, {4,5,6} {7,8,9}}

1 2 3
4 5 6
7 8 9

I want to shuffle the order of the row like this

4 5 6
7 8 9
1 2 3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the Fisher-Yates shuffle to swap the "rows" of the array. I used this answer for a 1d array and converted it to work with a 2d array:

public static void Shuffle(Random random, int[,] arr)
{
    int height = arr.GetUpperBound(0) + 1;
    int width = arr.GetUpperBound(1) + 1;

    for (int i = 0; i < height; ++i)
    {
        int randomRow = random.Next(i, height);
        for (int j = 0; j < width; ++j)
        {
            int tmp = arr[i, j];
            arr[i, j] = arr[randomRow, j];
            arr[randomRow, j] = tmp;
        }

    }
}

Try it online

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading