在不使用“集合”的情况下对2D阵列进行Shuffling
本文关键字:2D 阵列 Shuffling 情况下 集合 | 更新日期: 2023-09-27 18:20:53
我不知道如何在没有重复元素的情况下打乱2D数组。有人能帮我洗牌2D阵列吗?
以下是我目前所拥有的:
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();
}
}
}
好吧,我想说打乱2d数组的方式与打乱1d数组的方式相同。
例如,Fisher–Yates对1d数组的洗牌类似于
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]);
}
}
}
你所需要的只是意识到拥有一个2d阵列
T[,]阵列
以及访问阵列的元素
阵列[行,列]
row=索引/列计数
column=索引%columnCount
其中
index=[0],array.Lenght-1]对应于1d数组中的索引
columnCount=数组。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();
您需要首先通过随机数字序列对数组进行排序。您现在所做的只是在每次迭代时更改2d数组的两个随机项,因此可能会导致重复项。
看看1d数组的排序算法。
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] > arr[j]) // ran.Next(-1,1) == 0 // or any random condition
{
int temp = arr[i];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
正如您所看到的,我们需要2个循环来对1d数组进行排序。所以为了对2d数组进行排序,我们需要4个循环。
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(0); j++)
{
for (int k = 0; k < arr.GetLength(1); k++)
{
for (int l = 0; l < arr.GetLength(1); l++)
{
if (arr[i, k] > arr[j, l]) // ran.Next(-1,1) == 0
{
int temp = arr[i, k];
arr[i, k] = arr[j, l];
arr[j, l] = temp;
}
}
}
}
}
然后编写另一个算法来打印项目。
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + "'t");
}
Console.WriteLine();
}
这就是排序算法。现在,如果你只是用随机一个来改变这个条件,你就可以按随机对数组进行排序。
更改if (arr[i, k] > arr[j, l])
至if (ran.Next(-1,1) == 0)
。这只是随机的真或假。