c# - 如何在 C# 中打乱二维数组的行

标签 c#

例如,我有二维数组:

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

    }
}

Try it online

关于c# - 如何在 C# 中打乱二维数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69954685/

相关文章:

c# - 在 Azure AD 中的交互式身份验证中检索 2 个访问 token

c# - 基于抽象类型创建类

c# - ObjectStateManager 不包含引用类型对象的 ObjectStateEntry

c# - AllowHtml 属性不起作用

c# - 按名称动态获取/设置 C# 对象属性的最简单方法

c# - 列表框项目作为复选框

c# - 为 wp7 创建一个 pdf 阅读器

c# - Visual Studio 2010 C# "already defined a member with same parameter types error."

c# - Linq 自定义 OrderBy 使用常量

c# - 银光记忆