How to make this code work without repeating the n

2020-05-02 12:56发布

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

3条回答
何必那么认真
2楼-- · 2020-05-02 13:24

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>

查看更多
Juvenile、少年°
3楼-- · 2020-05-02 13:32

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();
    }
查看更多
太酷不给撩
4楼-- · 2020-05-02 13:39

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;
}
查看更多
登录 后发表回答