c# - 在不使用集合的情况下打乱二维数组

标签 c# multidimensional-array shuffle

我不知道如何在没有重复元素的情况下打乱二维数组。谁能帮我打乱二维数组?

这是我目前所拥有的:

public class Shuffle2DArray
{
    public Shuffle2DArray ()
    {
    }

    public static void Main(string[] args)
    {
        int[,] a = new int[3, 3] { { 1, 2, 3, }, { 6, 7, 8 }, { 11, 12, 13 } };

        Shuffle2DArray shuffle = new Shuffle2DArray ();
        shuffle.getshuffle2D (a);
    }

    void getshuffle2D(int[,] arr)
    {
        Random ran = new Random ();
        for (int i = 0; i < arr.GetLength (0);  i++) {

            for (int j = 0; j < arr.GetLength (1); j++) {
                int m = ran.Next(arr.GetLength (0)-1);
                int n = ran.Next(arr.GetLength (1)-1);

                int temp = arr[0,j];
                arr[i,0] = arr[m,n+1];
                arr[m,n] = temp;
                Console.Write(arr[i,j]+ "\t");
            }
            Console.WriteLine();
        }
    }
}

最佳答案

好吧,我会说像打乱一维数组一样打乱二维数组。

例如,Fisher–Yates shuffle一维数组是这样的

public static class Utils
{
    public static void Swap<T>(ref T a, ref T b) { var temp = a; a = b; b = temp; }
    public static void RandomShuffle<T>(this T[] target, Random random = null)
    {
        if (target.Length < 2) return;
        if (random == null) random = new Random();
        for (int i = target.Length - 1; i > 0; i--)
        {
            int j = random.Next(i + 1);
            if (i != j) Swap(ref target[i], ref target[j]);
        }
    }
}

所有你需要的是意识到拥有一个二维数组

T[,] array

并访问数组的元素

array[row, column]

那个

row = index / columnCount

column = index % columnCount

在哪里

index = [0, array.Lenght - 1] corresponds to the index in 1d array

columnCount = array.GetLength(1)

将 2d 版本函数添加到上面的类中是微不足道的

public static class Utils
{
    // ...
    public static void RandomShuffle<T>(this T[,] target, Random random = null)
    {
        if (target.Length < 2) return;
        if (random == null) random = new Random();
        int columnCount = target.GetLength(1);
        for (int i = target.Length - 1; i > 0; i--)
        {
            int j = random.Next(i + 1);
            if (i != j) Swap(ref target[i / columnCount, i % columnCount], ref target[j / columnCount, j % columnCount]);
        }
    }
}

示例用法:

int[,] a = new int[3, 3] { { 1, 2, 3, }, { 6, 7, 8 }, { 11, 12, 13 } };
a.RandomShuffle();

关于c# - 在不使用集合的情况下打乱二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561330/

相关文章:

python - 在 2D numpy 数组中有效地找到正值的索引范围

php - 计算重复数据并将其存储到变量中

c - 如何在文件中保存大量 C 中的数字

algorithm - 快速排序中的随机改组如何帮助提高代码效率?

c# - 改变 List<Point> 项的值

c# - 我的 O/R Designer 一直在删除 designer.cs 文件!

c# - 将数据存储在文件系统而不是 SQL 或 Oracle 数据库中

c# - 如何获取通用词典中的值?

c++ - 字符数组的初始化字符串太长

C++ - 洗牌 : required from here