Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I find impossible to get this code to work! I want to generate 10 numbers that are unique, but despite all I change, I get duplictates of numbers in the array! Would really preciate some help to solve this or improve the code, but I want it simple and easy to understand! Thanks!

int[] randomNumbers = new int[10];

        Random random = new Random();

        int index = 0;

        do
        {
            int randomNum = random.Next(0, 10);
            if (index == 0)
            {
                randomNumbers[0] = randomNum;
                index++;
            }

            else
            {
                for (int i = 0; i < randomNumbers.Length; i++)
                {
                    if (randomNumbers[i] == randomNum)
                        break;
                    else
                    {
                        randomNumbers[index] = randomNum;
                        index++;
                        break;
                    }
                }
            }
        }
        while (index <= 9);

        System.Console.WriteLine("Array ");
        foreach (int num in randomNumbers)
            System.Console.Write(num + " ");
share|improve this question
    
Just to clarify you want an array of non-duplicated random numbers? This is how I read the question the first time, but the answer given doesn't seem to make sense. –  Ray Dey Aug 16 '12 at 12:47
    
Yes I want non-duplicated random numbers! –  3D-kreativ Aug 16 '12 at 12:50
    
The main problem of your algorithm is that it can't work. Look at the for-loop. It essentially says if(A) { break; } else { break; }, so it will always break at i==0 and never execute twice or more, so you don't ever run through your whole array. So all you do is compare your new random numbers with the first one you created, and you insert it if it's different to the first one. –  Hackworth Aug 16 '12 at 13:45
add comment

closed as off topic by Tetrad Aug 16 '12 at 15:26

Questions on Game Development Stack Exchange are expected to relate to game development within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

3 Answers

up vote 2 down vote accepted

random.next(0, 10) returns a random number between 0 and 10. It can happen, that it returns the same number multiple times in a row and it is not guaranteed, that you get every number between 0 and 10 exactly one time, when you call it 10 times.

What you want is a list of numbers, every number is unique, between 0 and 9 (or 1 and 10). A possible solution to this would be something like this:

//Create the list of numbers you want
var list = new List<int>();
for(var x = 0; x < 10; x++)
{
    list.Add(x);
}

var random = new Random();
//Prepare randomized list
var randomizedList = new List<int>();
while(list.Length > 0)
{
    //Pick random index in the range of the ordered list
    var index = random.Next(0, list.Length);

    //Put the number from the random index in the randomized list
    randomizedList.Add(list[index]);

    //Remove the number from the original list
    list.RemoveAt(index);
}

Explained in words, this is what you do:

  1. Create the list with all the numbers, that your final list should contain
  2. Create a second empty list.
  3. Enter a loop. The loop continues, as long as the ordered list still has numbers in it.

    1. Pick a random index between 0 and list.Length
    2. Put this random number in the randomized list
    3. Remove the item at the index position from the ordered list.

Like this you create the set of numbers you want to have in your randomized list and then always pick a random entry from the ordered list. With this technique, you can also achieve, that certain values occur multiple time in the list.

I'm not sure if my code compiles against c#, as I currently do not have visual studio running here, but I think the code should be mostly correct.

share|improve this answer
    
"you can also achieve, that certain values occur multiple time in the list."?? But I want unique numbers!? With this code I will get duplicates! –  3D-kreativ Aug 16 '12 at 13:01
    
You can have duplicates if you want by adding a number multiple times to the list. But if you use my code you won't get any duplicates. What you do is you generate a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Then you create a second empty list. Then you pick one of the numbers from the first list at random, put it in the new list and remove it from the old. After 2 loop cycles, the first list could look like [0, 1, 3, 4, 5, 6, 7, 9] and the second is [9, 2]... After the next run it could be like [0, 1, 3, 4, 5, 7, 9] and the second is [9, 2, 6]. You just have to remove the number from the old list. –  tom van green Aug 16 '12 at 14:22
    
Btw, its basically an implementation of the fisher yates shuffle stated in another answer en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle –  tom van green Aug 16 '12 at 14:23
add comment

Something like this?

const int maxNumbers = 10;
List<int> numbers = new List<int>(maxNumbers);
for (int i = 0; i < maxNumbers; i++)
{
    numbers.Add(i);
}
Random r = new Random();
while (numbers.Count > 0)
{
    int index = r.Next(numbers.Count);
    Console.Write("{0} ", numbers[index]);
    numbers.RemoveAt(index);
}
Console.WriteLine();

Edit: For any random numbers:

const int maxNumbers = 10;
const int biggestNumbers = 10000;
List<int> numbers = new List<int>(maxNumbers);
Random r = new Random();
while (numbers.Count < maxNumbers)
{
    int index = r.Next(biggestNumbers);
    if (numbers.IndexOf(index) < 0)
    {
        numbers.Add(index);
        Console.Write("{0} ", index);
    }
}
Console.WriteLine();
share|improve this answer
    
Thanks, but there is still possible to get random numbers, isn't it? –  3D-kreativ Aug 16 '12 at 13:08
    
I edited my post to give you a hint on how to work with random numbers. –  Scoregraphic Aug 16 '12 at 13:22
    
Sorry, I meant there is still risk getting duplicates of numbers!? I'm a little bit tired after to many hours in front of computer! –  3D-kreativ Aug 16 '12 at 13:28
    
No duplicates are possible with this method (if biggestNumbers > maxNumbers). That's why the if (numbers.IndexOf(index) < 0) is there. –  Scoregraphic Aug 16 '12 at 13:33
add comment

The simplest way to have this is to have an array of the numbers you want (i.e. 1-10) and use a random shuffling algorithm.

The Fisher-Yates shuffle is the easiest way to do this.

EDIT:

Here's a link to a C# implementation: http://www.dotnetperls.com/fisher-yates-shuffle

share|improve this answer
    
Aha, you mean that for each time I remove the last number in the array or list of the number I want, and then the max number in random.Next is reduced!? –  3D-kreativ Aug 16 '12 at 12:56
    
That's not what I said at all, you may be referring to the other answer. –  Ray Dey Aug 16 '12 at 12:57
    
OK, but couln't my code be used at all? –  3D-kreativ Aug 16 '12 at 13:10
    
I don't need to shuffle an array, I just want ten or more random numbers that are unique and store them in a array ant then pick each number when I want. I didn't thought it should be that complicated!? –  3D-kreativ Aug 16 '12 at 13:15
5  
Shuffling an array from 1 to 10 results in the same thing as generating a random array of unique numbers from 1 to 10. It's just more efficient. I don't know if you're misunderstanding how random numbers work or what, but Ray Dey has given you the solution to your problem. –  Byte56 Aug 16 '12 at 13:17
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.