Random always returning the same number

6

I have a method whose function is to return 25 random numbers in a list:

static List<int> criarList()
{
    List<int> lista = new List<int>();
    for (int i = 0; i < 25; i++)
    {
        lista.Add(new Random().Next(0, 100));
    }
    return lista;
}

But for some reason, it only returns the same numbers, ie all the same:

Why is this happening? How to arrange?

    
asked by anonymous 28.10.2017 / 21:06

1 answer

7

The Random class uses an algorithm to generate the sequence of random (pseudo) numbers. This sequence is started based on a value called seed . Different values generate different sequences.

The Random () constructor uses the system clock to get the seed .

As you are building multiple instances in a short space of time seed is always the same, always originating the same sequence.

Use only one instance:

static List<int> criarList()
{
    List<int> lista = new List<int>();
    var random = new Random();
    for (int i = 0; i < 25; i++)
    {
        lista.Add(random.Next(0, 100));
    }
    return lista;
}
    
28.10.2017 / 21:16