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.
>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);
}