Random always returning the same number

Asked

Viewed 430 times

6

I have a method that its function is to return 25 random numbers on 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, that is, all the same:

inserir a descrição da imagem aqui

Why is this happening? How to fix?

  • 1

    The class Random appears to generate a sequence of numbers that meet certain statistical randomness requirements. The sequence is generated from a standard seed, based on time. Wouldn’t it be the problem that all instances of the class are using the same seed and thus generating the same sequence? Why don’t you call the method Next of the same instance 25 times?

1 answer

7


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

The builder Random() uses the system clock to obtain the Seed.

How are you to build multiple instances in a short span of time the 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.