在数组中生成并存储7个随机数

时间:2019-11-14 17:43:32

标签: c#

我制作了一个程序,使用数组为彩票生成7个随机数。我生成了一个介于1,50之间的随机数,但是每个数字按顺序显示,而不是在同一行上。我还想将自动生成的数字存储在数组中以供使用。我不确定如何解决此问题,将不胜感激

10000 x log(2) + 1 = 3011

3 个答案:

答案 0 :(得分:1)

这是您需要的吗?

static void AutoGenrateNumbers()
{
    int temp;
    int[] lotto = new int[7];

    Random rand = new Random();

    for (int i = 0; i < 7; i++)
    {
        temp = rand.Next(1, 50);
        lotto[i]= temp;
    }
    Console.Write($"the new lotto winning numbers are: ");

    for (int i = 0; i < 6; i++)
    {
        Console.Write(lotto[i]+" ");
    }
    Console.Write($"Bonus:{lotto[6]}");

}

编辑:如果您希望数字唯一:

static void AutoGenrateNumbers()
{
    int temp;
    int[] lotto = new int[7];

    Random rand = new Random();

    for (int i = 0; i < 7; i++)
    {
        do
        {
            temp = rand.Next(1, 50);
        }
        while (lotto.Contains(temp));
        lotto[i]= temp;
    }

    Console.Write($"the new lotto winning numbers are: ");
    for (int i = 0; i < 6; i++)
    {
        Console.Write(lotto[i]+" ");
    }
    Console.Write($"Bonus:{lotto[6]}");

}

答案 1 :(得分:1)

一种更好的方法是生成所有数字1-50,将它们洗牌然后取7。使用Jon Skeet的Shuffle扩展方法here

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
    T[] elements = source.ToArray();
    for (int i = elements.Length - 1; i >= 0; i--)
    {
        int swapIndex = rng.Next(i + 1);
        yield return elements[swapIndex];
        elements[swapIndex] = elements[i];
    }
}

现在您的代码非常简单:

static void AutoGenrateNumbers()
{
    var lotto = Enumerable.Range(0, 50).Shuffle(new Random()).Take(7);
    Console.WriteLine("the new lotto winning numbers are: {0}", string.Join(",", lotto));
}

提琴here

答案 2 :(得分:0)

只需在一条LINQ语句中添加尝试添加到现有答案中即可:

static void Main(string[] args)
{
    var rand = new Random();
    Enumerable
        .Range(1, 7)
        .Aggregate(new List<int>(), (x, y) =>
        {
            var num = rand.Next(1, 51);
            while (x.Contains(num))
            {
                num = rand.Next(1, 51);
            }
            x.Add(num);
            return x;
        })
        .ForEach(x => Console.Write($"{x} "));
}

结果类似于:

34 24 46 27 11 17 2