我正在尝试随机化二维数组中的一组预定元素。
using System;
namespace array
{
public class tiles
{
static void Main(string[] args)
{
Random random = new Random();
int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(tilearr[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
我的问题是,如果我执行类似 tilearr[i, j] = random.Next(0, 8);
的操作,它会随机化数组但不关心是否有任何重复项相同的元素。
2 6 7
1 1 3
2 7 0
我追求的更像这样:
2 4 8 1 3 0
0 3 1 5 6 8
6 7 5, 2 4 7
最佳答案
一个简单而切题的解决方案是拥有一个可用号码列表,然后逐个位置并从列表中随机选择号码。
像这样:
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
for(int x = 0; x < 3; ++x) {
for(int y = 0; y < 3; ++y) {
// select a random number from the list ...
int rand = random.Next(0, numbers.Count - 1);
tilearr[x, y] = numbers[rand];
// ... and remove it from the list
numbers.RemoveAt(rand);
}
}
关于c# - 使用 Random 类随机化二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60491678/