在不使用 Collections 的情况下打乱 2D 数组

2024-02-11

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

这是我到目前为止所拥有的:

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

好吧,我想说的是,以与洗牌一维数组相同的方式洗牌二维数组。

例如,费舍尔-耶茨洗牌 https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_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[] 数组

并访问数组的元素

数组[行,列]

that

行=索引/列数

列 = 索引 % 列数

where

index = [0, array.Length - 1] 对应于一维数组中的索引

列计数 = 数组.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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在不使用 Collections 的情况下打乱 2D 数组 的相关文章

随机推荐