Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

random Numbergenerator 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 differnet from eachother 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. Thats why i am asking for advice or for an idea, how to do it better than me.

Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way to solve it would be to simulate what a real lotto machine does.

First, put the 49 balls in the bucket:

var bucket = Enumerable.Range(1, 49).ToList();

Then in a loop, determine a random index in the current bucket, get the number at this index and remove it so that it cannot be drawn again

var random = new Random();
for (var i = 0; i < 6; i++)
{
    var index = random.Next(bucket.Count);
    var number = bucket[index];
    Console.WriteLine(number);
    bucket.RemoveAt(index);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading