jeudi 11 août 2022

Random number generator with different numbers

I am currently working on one of my first projects in C#. Right now i want to create something like a lottomachine. It should output 6 numbers all different from each other in the range of 1-49.

private void random()
{
    Random rnd = new Random();
    z1 = rnd.Next(1, 49);
    z2 = rnd.Next(1, 49);
    if (z1 == z2)
    {
        z2 = rnd.Next(1, 49);
    }
    z3 = rnd.Next(1, 49);
    if ((z1 == z3) || (z2 == z3))
    {
        z3 = rnd.Next(1, 49);
    }
    z4 = rnd.Next(1, 49);
    if ((z1 == z4) || (z2 == z4) || (z3 == z4))
    {
        z4 = rnd.Next(1, 49);
    }
    z5 = rnd.Next(1, 49);
    if ((z1 == z5) || (z2 == z5) || (z3 == z5) || (z4 == z5))
    {
        z5 = rnd.Next(1, 49);
    }
    z6 = rnd.Next(1, 49);
    if ((z1 == z6) || (z2 == z6) || (z3 == z6) || (z4 == z6) || (z5 == z6))
    {
        z6 = rnd.Next(1, 49);
    }
}

The code is working for me currently, but I think there is a better, much shorter way what my code does. That's why I am asking for advice or for an idea, how to do it better than me.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire