Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - Unique number in random?

I know there are many questions on the net about it ,but I would like to know why my method fails What Am i Doing wrong?

public class Generator
{

    private static readonly Random random = new Random();

    private static readonly object SyncLock = new object();

    public static int GetRandomNumber(int min, int max)
    {
        lock (SyncLock)
        { 
            return random.Next(min, max);
        }
    }

}


[TestFixture]
public class Class1
{
    [Test]
    public void SimpleTest()
    {

        var numbers=new List<int>();
        for (int i = 1; i < 10000; i++)
        {
            var random = Generator.GetRandomNumber(1,10000);
            numbers.Add(random);
        }

        CollectionAssert.AllItemsAreUnique(numbers);

    }
}

EDIT Test method is failing!! Sorry for not mentioning

Thanks for your time and suggestions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How can you possibly expect a sequence of 10,000 random numbers from a set of 10,000 possible values to be all unique unless you are extremely lucky? What you are expecting is wrong.

Flip a coin twice. Do you truly expect TH and HT to be the only possible sequences?

What makes you think random numbers should work any differently?

This output from a random number generator is possible:

1, 1, 1, 1, 1, 1, ..., 1

So is this:

1, 2, 3, 4, 5, 6, ..., 10000

In fact, both of those sequences are equally likely!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...