gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:34:08 29 4
gpt4 key购买 nike

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

这是我目前所拥有的:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com