-1

I have a 2D string array.

I just want to randomize the rows order and shuffle the items within each row.

So for example:

[1,2
 3,4]

I want it to be as below, row pairs stay same here (order change is valid):

[4,3
 1,2] or
[3,4
 2,1] or
[4,3
 2,1] or
[1,2
 3,4] or
[2,1
 3,4] or
[2,1
 4,3] or
[3,4
 1,2] 

and i want to avoid below shuffling because i'll read my array row by row, i want to keep my rows to contain same elements. I want to keep my row pairs. Below, my [1,2] and [3,4] rows does not exist anymore :

[1,3
 2,4] or 
[3,1
 4,2] or 
[3,1
 2,4] or
[1,4
 2,3] ....

So here is my array:

array_to_shuffle = new string[len_2d,2];
Shuffle(array_to_shuffle);

and the function i need help :

    public void Shuffle(Random rand, string[,] array)
    {
        rand = new Random();
        int[] randomised_array = new int[len_2d];

        for (int i = 0; i < len_2d; i++)
        {
            randomised_array[i] = i;
        }
        int[] MyRandomArray = randomised_array.OrderBy(x => rand.Next()).ToArray();
        string tmp1 = String.Empty;
        string tmp2 = String.Empty;

        array[MyRandomArray[0], 0] = tmp1;
        array[MyRandomArray[0], 1] = tmp2;

        array[MyRandomArray[0], 0] = array[MyRandomArray[1],0];
        array[MyRandomArray[0], 1] = array[MyRandomArray[1],1];
        array[MyRandomArray[1], 0] = tmp2;
        array[MyRandomArray[1], 1] = tmp1;


    }

Thank you everyone...

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69

1 Answers1

1

Try this code (necessary comments are in code):

static void Main(string[] args)
{
    int[,] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }, { 9, 10 }, { 11, 12 } };
    matrix = Shuffle(matrix);
}

static T[,] Shuffle<T>(T[,] matrix)
{
    int howManyRows = matrix.GetLength(0);
    int howManyColumns = matrix.GetLength(1);
    T[,] randomizedMatrix = new T[howManyRows, howManyColumns];
    //we will use those arrays to randomize indexes
    int[] shuffledRowIndexes = Enumerable.Range(0, howManyRows).ToArray();
    int[] shuffledColumnIndexes = Enumerable.Range(0, howManyColumns).ToArray();
    Random rnd = new Random();
    shuffledRowIndexes = shuffledRowIndexes.OrderBy(x => rnd.Next()).ToArray();

    for (int i = 0; i < howManyRows; i++)
    {
        // at every loop we get new randomized column idexes, so every row will be shuffled independently
        shuffledColumnIndexes = shuffledColumnIndexes.OrderBy(x => rnd.Next()).ToArray();
        for (int j = 0; j < howManyColumns; j++)
            randomizedMatrix[i, j] = matrix[shuffledRowIndexes.ElementAt(i), shuffledColumnIndexes.ElementAt(j)];
    }

    return randomizedMatrix;
}

Helpful articles:

Best way to randomize an array with .NET

What are the differences between a multidimensional array and an array of arrays in C#?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • It super helped, your variable names helped me to understand. Makes a lot of sense. Thank you so much sir! –  Sep 01 '18 at 11:34