0

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...

1

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

beat me to it. shouldn't have spent time editing the question...
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(); 

1 Comment

It's risky to order by NewGuid - as results wont be uniformly random

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.