gpt4 book ai didi

c# - 将随机数输入无重复的二维数组

转载 作者:行者123 更新时间:2023-11-30 22:51:24 25 4
gpt4 key购买 nike

我想在一个 8*8 数组中输入 64 个不同的数字,但我遇到了问题...

int[,] check = new int[8, 8];
Random rnd = new Random();
int[,] T = new int[8, 8];
for (int i = 0; i <=7; i++)
{
for (int j = 0; j <=7; j++)
{
int num = rnd.Next(1, 64);
check[i, j] = num;
while (num != check[i,j])
{
T[i, j] = num;

}
Console.Write("{0}\t", T[i, j]);
}
Console.Write("\n\n");
}

最佳答案

尝试将数字 0 到 63 随机分配给数组:

    class Program
{
const int ROWS = 8;
const int COLS = 8;
static void Main(string[] args)
{
Random rnd = new Random();

int[] values = Enumerable.Range(0, ROWS * COLS)
.Select(x => new { number = x, rand = rnd.Next()})
.OrderBy(x => x.rand)
.Select(x => x.number).ToArray();

int[,] T = new int[ROWS, COLS];

int count = 0;
for(int row = 0; row < ROWS; row++)
{
for(int col = 0; col < COLS; col++)
{
T[row, col] = values[count++];
}
}

}

关于c# - 将随机数输入无重复的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225153/

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