How to make this code work without repeating the n

2020-05-02 13:06发布

问题:

This question already has answers here:
Closed 6 years ago.

I need to print numbers from 1 to 50 in random order without repeating it .

static void Main(string[] args)
{
     ArrayList r = new ArrayList();

     Random ran = new Random();      
     for (int i = 0; i < 50; i++)
     {
        r.Add(ran.Next(1,51));

     }

     for (int i = 0; i < 50; i++)
        Console.WriteLine(r[i]);
     Console.ReadKey();
}

回答1:

All you need to do is this check if the number already exists in the list and if so get another one:

static void Main(string[] args)
{
    ArrayList r = new ArrayList();

    Random ran = new Random();      
    int num = 0;

    for (int i = 0; i < 50; i++)
    {
        do { num = ran.Next(1, 51); } while (r.Contains(num));
        r.Add(num);
    }

    for (int i = 0; i < 50; i++)
       Console.WriteLine(r[i]);

    Console.ReadKey();
}

Edit: This will greatly increase the effeciency, preventing long pauses waiting for a non-collision number:

    static void Main(string[] args)
    {
        List<int> numbers = new List<int>();

        Random ran = new Random();
        int number = 0;
        int min = 1;
        int max = 51;

        for (int i = 0; i < 50; i++)
        {
            do
            {
                number = ran.Next(min, max);
            }
            while (numbers.Contains(number));

            numbers.Add(number);

            if (number == min) min++;
            if (number == max - 1) max--;
        }

        for (int i = 0; i < 50; i++)
            Console.WriteLine(numbers[i]);

        Console.ReadKey();
    }


回答2:

What you want here is the Fisher Yates Shuffle

Here is the algorithm as implemented by Jeff Atwood

cards = Enumerable.Range(1, 50).ToList();
for (int i = cards.Count - 1; i > 0; i--)
{
  int n = ran.Next(i + 1);
  int temp = cards[i];
  cards[i] = cards[n];
  cards[n] = temp;
}


回答3:

If you don't want to repeat the numbers between 1 and 50, your best bet is to populate a list with the numbers 1 to 50 and then shuffle the contents. There's a good post on shuffling here: Randomize a List<T>