例如,我有二维数组:
int[,] array = new int[3,3] {{1,2,3}, {4,5,6} {7,8,9}}
1 2 3
4 5 6
7 8 9
我想像这样打乱行的顺序
4 5 6
7 8 9
1 2 3
最佳答案
您可以使用 Fisher-Yates shuffle 来交换数组的“行”。我用过this answer对于一维数组并将其转换为与二维数组一起使用:
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;
}
}
}
关于c# - 如何在 C# 中打乱二维数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69954685/