Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...