Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-repetitive random number

Tags:

c#

random

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

Random rnd = new Random()
rnd.Next(1,20)
for(int i =0; i<=20;i++)
{

}

For all the loops number should be 1 to 20

like image 273
web dunia Avatar asked Jun 18 '09 07:06

web dunia


2 Answers

I did one this way awhile back. I don't know how it compares to the other methods presented as far as efficiency, randomness, etc. But it seems to work:

List<int> integers = new List<int>() { 1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12 };

Random rnd = new Random();

var ints = from i in integers
           orderby rnd.Next(integers.Count)
           select i;
like image 139
Chris Dunaway Avatar answered Sep 19 '22 13:09

Chris Dunaway


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

/// <summary>
/// Returns all numbers, between min and max inclusive, once in a random sequence.
/// </summary>
IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
{
    List<int> candidates = new List<int>();
    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);
}
like image 39
Hallgrim Avatar answered Sep 22 '22 13:09

Hallgrim