Creating an object with a random internal datum (Random)

Asked

Viewed 105 times

0

I am trying to create an object called "State", however I would like the DDD of each object, when creating, to be generated randomly.

class Estado
{
    public int Resultado { get; set; }
    public string Nome { get; set; }

    public Estado(string nome)
    {
        Nome = nome;
        rnd();
    }
    public void rnd()
    {
        Random random = new Random();
        Resultado = random.Next(0, 101);
    }
    public override string ToString()
    {
        return "Estado: "+Nome+"\nDDD: "+Resultado;
    }
}

But as we spin:

 static void Main(string[] args)
    {
        Estado pe = new Estado("Pernambuco");
        Estado pa = new Estado("Pará");
        Estado pi = new Estado("Piauí");
        Estado pr = new Estado("Paraná");

        Console.WriteLine(pe.ToString());
        Console.WriteLine(pa.ToString());
        Console.WriteLine(pi.ToString());
        Console.WriteLine(pr.ToString());
        Console.ReadLine();
    }

The result came out repeated:

State: Pernambuco

DDD: 60

State: Pará

DDD: 60

State: Piauí

DDD: 60

State: Paraná

DDD: 60

How can I do for each object, when creating the constructor, have its own randomly generated DDD?

  • Tip: http://www.macoratti.net/12/05/c_rand1.htm

  • The reason is that it creates only one object by execution. Unless you repeat dry per line.To facilitate understanding, your result (ramdom) is being executed only once. If it were inside a for() or calling the object each state would run unlimited times. Therefore Voce has only one generated number. Time as the colleague said does not influence anything. To do the test, in place of toString put Random() is more or less like this.Writeline(pa.Random())

1 answer

2


It’s because you’re instantiating several Random in a super short time period (less than a millisecond), and there is no time for the Random alternate its seed, and consequently generate a random number different from those previously instantiated.

What you can do, is catch a single instance of Random and not to instantiate several, but only one, which will be global to all other uses. Also, lock your Thread so it cannot run simultaneously (and avoid generating the same number consecutively)

// dentro da Program, ou qualquer classe estática/não estática
public static Random random = new Random();

class Estado
{
    public int Resultado { get; set; }
    public string Nome { get; set; }

    public Estado(string nome)
    {
        Nome = nome;
        rnd();
    }
    public void rnd()
    {
        lock (Program.random) { // evita que o 'random' seja utilizado em threads simultâneos
            Resultado = Program.random.Next(0, 101);
        }
    }
    public override string ToString()
    {
        return "Estado: "+Nome+"\nDDD: "+Resultado;
    }
}

The Next() will always be a pseudo-random number in relation to what was generated earlier, if the seed is the same.

Documentation of Random.

Documentation of Lock.

Browser other questions tagged

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