2

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

4 Answers4

3

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

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
0

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/

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • This seems different to what OP wants. You're randomizing everything in the array, but OP just seems to want to randomize the rows. – ProgrammingLlama Nov 13 '21 at 13:42
0

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.

karakale
  • 126
  • 11
0

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

smolchanovsky
  • 1,775
  • 2
  • 15
  • 29