改组2D阵列

时间:2018-09-01 09:39:52

标签: c# arrays random shuffle

我有一个二维字符串数组。

我只想随机化行顺序并随机排列每行中的项目。

例如:

[1,2
 3,4]

我希望它如下所示,行对在这里保持不变(顺序更改有效):

[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] 

并且我想避免在改组中,因为我将逐行读取数组,我想保持行中包含相同的元素。我想保持行对。在下面,我的[1,2]和[3,4]行不再存在:

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

这是我的数组:

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

和我需要帮助的功能:

    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;


    }

谢谢大家...

1 个答案:

答案 0 :(得分:1)

尝试以下代码(必要的注释在代码中):

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;
}

有用的文章:

Best way to randomize an array with .NET

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