Home > Software engineering >  How to shuffle the rows of a 2d array in C#
How to shuffle the rows of a 2d array in C#

Time:11-13

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

CodePudding user response:

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

CodePudding user response:

You could shuffle a given array using the Fisher–Yates shuffle Algorithm

public static void Shuffle(Random random, int[,] arr)
{
    int rowLen = arr.GetLength(1);

    for (int i = arr.Length - 1; i > 0; i--)
    {
        int i0 = i / rowLen;
        int i1 = i % rowLen;

        int j = random.Next(i   1);
        int j0 = j / rowLen;
        int j1 = j % rowLen;

        int temp = arr[i0, i1];
        arr[i0, i1] = arr[j0, j1];
        arr[j0, j1] = temp;
    }
}
 
int[,] array = new int[3,3] {{1,2,3}, {4,5,6} {7,8,9}}
Random rnd = new Random();

Shuffle(rnd, array);

Read more about the algorithm here - https://www.geeksforgeeks.org/shuffle-a-given-array-using-fisher-yates-shuffle-algorithm/

CodePudding user response:

You can generate a random sequence with length of row count by using this answer

How to generate random sequence of numbers between a given range

Then, by using a temp row you can change the order of rows.

CodePudding user response:

The elegant way to do this is using a list:

var listOfArrays = new List<int[]> { new[] {1,2,3}, new[] {4,5,6}, new[] {7,8,9} };
var shuffledListOfArrays = listOfArrays.OrderBy(_ => Guid.NewGuid()).ToList();
shuffledListOfArrays.ForEach(x => Console.WriteLine(string.Join(separator: " ", x)));

Link: https://dotnetfiddle.net/rULe8d

  •  Tags:  
  • c#
  • Related