简体   繁体   中英

Generate some unique numbers and put into array

I'm trying to create a method that produces 10 unique random numbers, but the numbers are not unique, I get several duplicates! How can I improve the code to work as I want?

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

foreach (int num in randomNumbers)
            System.Console.Write(num + " ");

EDIT 2: I have corrected all errors now, but this code isn't working becuase the numbers are not unique! I have updated my code above to the latest version. I preciate some help to solve this! Thanks!

The simplest way to have this is to have an array of the numbers you want (ie 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM