Non-repetitive random number

后端 未结 10 1939
囚心锁ツ
囚心锁ツ 2020-11-27 08:10

To generate Random numbers from 1- 20 I need to pick selective and it should not be repetitive.

How to do this in C#

Note I need to loop through as like this

10条回答
  •  甜味超标
    2020-11-27 09:17

    This method will generate all the numbers, and no numbers will be repeated:

    /// 
    /// Returns all numbers, between min and max inclusive, once in a random sequence.
    /// 
    IEnumerable UniqueRandom(int minInclusive, int maxInclusive)
    {
        List candidates = new List();
        for (int i = minInclusive; i <= maxInclusive; i++)
        {
            candidates.Add(i);
        }
        Random rnd = new Random();
        while (candidates.Count > 0)
        {
            int index = rnd.Next(candidates.Count);
            yield return candidates[index];
            candidates.RemoveAt(index);
        }
    }
    

    You can use it like this:

    Console.WriteLine("All numbers between 0 and 20 in random order:");
    foreach (int i in UniqueRandom(0, 20)) {
        Console.WriteLine(i);
    }
    

提交回复
热议问题