在不使用集合的情况下混洗

在不使用集合的情况下混洗

本文介绍了在不使用集合的情况下混洗 2D 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know how to shuffle 2D array without duplicate elements. Can anyone help me to shuffle a 2D array?

这是我目前所拥有的:

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

推荐答案

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

Well, I would say shuffle the 2d array the same way as you shuffle the 1d array.

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

For instance, Fisher–Yates shuffle for 1d array is something like this

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

你只需要意识到拥有一个二维数组

All you need is to realize that having a 2d array

T[,] 数组

并访问数组的元素

数组[行,列]

那个

row = index/columnCount

列 = 索引 % columnCount

column = index % columnCount

哪里

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

columnCount = array.GetLength(1)

columnCount = array.GetLength(1)

在上面的类中添加二维版本函数很简单

adding the 2d version function to the class above is trivial

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

这篇关于在不使用集合的情况下混洗 2D 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:29