当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Algorithm to get 9 different numbers in an array

问题描述:

This question already has an answer here:

  • Is using Random and OrderBy a good shuffle algorithm?

    12 answers

网友答案:

It sounds to me, like you may be better-off starting with your list of 1..9 - and shuffling it, to get a random order.

Use a Fisher–Yates shuffle

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;
}
网友答案:

If you know what values you're needing then just OrderBy and it will randomise them.

var numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
var shuffled = numbers.OrderBy(a => System.Guid.NewGuid()).ToArray();
分享给朋友:
您可能感兴趣的文章:
随机阅读: