Algorithm to get 9 different numbers in an array

时间:2015-05-24 21:29:23

标签: c# algorithm

I need help to create an algorithm to make 9 random numbers. Each number must not be equal to any other. Restated as 9 random numbers from 1-9.

I had something like this in mind:

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;
}

I had a method that had ifs inside for loops inside while loops inside foreach loops and such...

2 个答案:

答案 0 :(得分:6)

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;
}

答案 1 :(得分:0)

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();