在一个数组中得到9个不同数字的算法

本文关键字:9个 数字 算法 数组 一个 | 更新日期: 2023-09-27 17:50:45

我需要帮助创建一个算法,使9个随机数。每个数字不能等于任何其他数字。重新表述为1-9中的9个随机数

我有这样的想法:

int[] numlist = new int[9];
Random rand = new Random();
int temp;
foreach (int i in numlist) {
    temp = rand.Next(1, 10);
    //check if temp is already a value of a lower index in numlist
        //if so, rolls another random number and checks it again...
    numlist[i] = temp;
}

我有一个方法里面有if s for循环里面有while循环里面有foreach循环等等

在一个数组中得到9个不同数字的算法

听起来,你最好从你的清单1开始。9 -然后洗牌,得到一个随机的顺序。

使用Fisher-Yates洗牌

var random = new Random();
int[] array = Enumerable.Range(1, 9).ToArray();
for (int i = array.Length; i > 1; i--)
{
    // Pick random element to swap.
    int j = random.Next(i); // 0 <= j <= i-1
    // Swap.
    var tmp = array[j];
    array[j] = array[i - 1];
    array[i - 1] = tmp;
}

如果你知道你需要什么值,那么只需排序,它会随机化它们。

var numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
var shuffled = numbers.OrderBy(a => System.Guid.NewGuid()).ToArray();