Iam*_*Man 2 c# arrays random debugging 2d
对于某些课程,我需要通过蛮力生成一个普通的魔方,这是代码的一部分.仅供参考; 我不允许使用除常用之外的任何类.(我可能用Math.Pow推动我的运气)
我有以下方法来生成2维大小NxN:
static int[,] GenerateSquare(int n)
{
int[,] sqarray = new int[n,n];
int[] rndarray = new int[n];
//puts completely random integers from 1 to n^2 in all elements of the square array (sqarray)
for (int i = 0; i < n; i++)
{
rndarray = FullRndArray(n);
for (int j = 0; j < n; j++)
{
sqarray[i, j] = rndarray[j];
}
}
return sqarray;
}
Run Code Online (Sandbox Code Playgroud)
FullRndArray()方法如下:
static int[] FullRndArray(int n)
{
//creates an array of size n and fills with random intigers between 1 and n^2
int[] rndarray = new int[n];
Random rnd = new Random();
int ntothe2 = Convert.ToInt32(Math.Pow(n, 2));
for (int i = 0; i < n; i++)
rndarray[i] = rnd.Next(1, ntothe2 + 1);
return rndarray;
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我运行此代码时,每行的内容是随机的,但是方块的每一行与最后一行相同(即1-1,1-2,1-3与2-1相同) ,2-2,2-3和3-1,3-2,3-3分别相同).然而,当我逐行检查调试器时,我最终会在每个空间中得到一组完全随机的数字.有人可以向我解释这个错误吗?
这是罪魁祸首:
Random rnd = new Random();
Run Code Online (Sandbox Code Playgroud)
从种子开始生成随机数:相同的种子意味着相同的非随机数字序列.Random
使用当前时间作为种子,因此当您运行代码时,它运行得如此之快,以至于您Random
使用相同的种子创建两个s,然后生成两个相同的行.另一方面,在调试时,让足够的时间过去,一切都按预期进行.
解决方案是创建Random
静态或开头的实例GenerateSquare
,并将其用于整个过程.