I have a lottery game where I can generate 1 set of 6 numbers.I am trying to generate two sets of 6 numbers but am unable to do so.
public static void LottoDraw()
{
int[] lotto = new int[6];
Random LottoNumbers = new Random();
for (int i = 0; i < lotto.Length; i )
{
lotto[i] = LottoNumbers.Next(1, 47);
}
Array.Sort(lotto);
Console.WriteLine("Your Lotto Numbers are:");
for (int i = 0; i < lotto.Length; i )
Console.WriteLine(lotto[i]);
Console.ReadLine();
}
I tried using a while loop but the variables "line1" and "line2" as seen here Generating 2 Random Numbers that are Different C# but kept generating errors as
CodePudding user response:
Let's shuffle 1 .. 46
numbers and take 6
of them (in order to avoid duplicates). Then we can Join
these taken numbers to show on the console:
using System.Linq;
...
// Simplest, but not thread safe
// use Random.Shared if your c# version supports it
private static readonly Random random = new Random();
...
public static void LottoDraw()
{
var lotto = Enumerable
.Range(1, 46)
.OrderBy(_ => random.Shared.NextDouble())
.Take(6)
.OrderBy(item => item)
.ToArray();
Console.WriteLine(string.Join(Environment.NewLine, lotto));
Console.ReadLine();
}
CodePudding user response:
Lets write a method which creates lotto sets:
public static List<int> GenerateLottoSet(int n)
{
var random = new Random();
return Enumerable.Range(0, n).Select(_ => random.Next(1, 47)).ToList();
}
and then call it as many times as you need:
var set1 = GenerateLottoSet(6);
var set2 = GenerateLottoSet(6);