Non-repetitive random number

2019-01-07 00:39发布

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

标签: c# random
9条回答
迷人小祖宗
2楼-- · 2019-01-07 00:53

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;
查看更多
Summer. ? 凉城
3楼-- · 2019-01-07 00:54
class Program
{
    static void Main(string[] args)
    {        
        List<int> list = new List<int>();
        int val;
        Random r;
        int IntialCount = 1;
        int count = 7 ;
        int maxRandomValue = 8;

        while (IntialCount <= count)
        {
            r = new Random();
            val = r.Next(maxRandomValue);
            if (!list.Contains(val))
            {
                list.Add(val);
                IntialCount++;
            }

        } 
    }
}
查看更多
Root(大扎)
4楼-- · 2019-01-07 00:54

blow code generates 65 unique random number between 0 - 92 and return that unique random numbers in an array.

public static int[] RandomNumbers_Supplier()
        {
            Random R = new Random();
            int[] RandomNumbers = new int[65];
            int k = 0, Temp;
            bool IsRepetitive = false;
            while (k < 65)
            {
                Temp = R.Next(0, 92);
                for (int i = 0; i < 65; i++)
                {
                    IsRepetitive = false;
                    if (RandomNumbers[i] == Temp)
                    {
                        IsRepetitive = true;
                        break;
                    }                    
                }
                if (!IsRepetitive)
                {
                    RandomNumbers[k] = Temp;
                    k++;
                }
            }
            return(RandomNumbers)
        }
查看更多
别忘想泡老子
5楼-- · 2019-01-07 00:59

From MSDN

"One way to improve randomness is to make the seed value time-dependent."

Another fact

you should "create one Random to generate many random numbers over time." This will enhance the random generation

查看更多
做自己的国王
6楼-- · 2019-01-07 01:00

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);
}
查看更多
Evening l夕情丶
7楼-- · 2019-01-07 01:04

What exactly do you mean by "should not be repetitive"? If you mean that you don't want to get any duplicates, then you should basically take a list of the numbers 1-20, shuffle them, and then grab one at a time from the head of the list. For an efficient way to shuffle a list, see this Stack Overflow answer.

If you just mean that your current attempt gives 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 etc then chances are you're creating a new instance of Random each time you pick a number: don't do that. Each time you create an instance, it will use the current time as the "seed" for the random number generator (unless you specify one explicitly). That means if you create several instances in quick succession, each will get the same seed and therefore give the same sequence of numbers.

Instead, use a single instance of Random and reuse it. (Note that it's not thread-safe though, which is a pain.) For instance:

private static readonly Random Rng = new Random();

public int NextNumber()
{
    return Rng.Next(20) + 1;
}

That won't be thread-safe, but let us know if that's a problem. An alternative is sometimes to pass the Random into the method (which would normally be more complicated, of course):

public int NextNumber(Random rng)
{
    return rng.Next(20) + 1;
}

then the caller can reuse the instance appropriately.

If you want a thread-safe way of generating random numbers, you might want to look at my StaticRandom class in MiscUtil.

(Note that using rng.Next(1, 21) would also work fine - I happen to prefer the version above as I think it reduces the guesswork about inclusive/exclusive boundaries, but it's a matter of personal taste.)

查看更多
登录 后发表回答