簡體   English   中英

如何生成五組隨機數

[英]How to generate five sets of random numbers

我正在嘗試按最高數字和逗號分隔以 c# 順序生成五組隨機數

我嘗試使用

public static void Main(string[] args)
{
    int[] randNumber = new int[5];
    Random rand = new Random();
    Console.Write("The random numbers are: "); 
    for (int h = 0; h < randNumber.Length; h++)
    {
        randNumber[h] = rand.Next(1, 20);           
    } 
    Console.Write(string.Join(", ", randNumber));        
}

我只得到一組輸出而沒有排序(從最高到最低)即

隨機數是:12, 2, 12, 19, 11

預期輸出應該是這樣的:

  1. 11、9、7、6、4
  2. 13、8、7、6、4
  3. 13、9、7、6、2
  4. 17.9,7,6,1
  5. 1、6、7、4、14

只是增強了您的代碼。

class Program
    {
        static void Main(string[] args)
        {
            int[] randNumber = new int[5];
            Random rand = new Random();
            Console.WriteLine("The random numbers are: ");
            for (int i = 0; i < 5; i++)
            {
                for (int h = 0; h < randNumber.Length; h++)
                {
                    randNumber[h] = rand.Next(1, 20);
                }
                randNumber = randNumber.OrderByDescending(x => x).ToArray();
                Console.WriteLine(string.Join(", ", randNumber));
            }
        }
    }

另一個...

static void Main(string[] args)
{
    Random R = new Random();
    List<List<int>> sets = new List<List<int>>();
    for(int s=1; s<=5; s++)
    {
        List<int> set = new List<int>();
        for (int i = 1; i <= 5; i++)
        {
            set.Add(R.Next(1, 20));
        }
        set.Sort();
        set.Reverse();
        sets.Add(set);
    }

    for(int i=1; i<=sets.Count; i++)
    {
        Console.WriteLine(i.ToString() + ". " + string.Join(", ", sets[i-1]));
    }

    Console.Write("Press Enter to quit");
    Console.ReadLine();
}

示例輸出:

1. 19, 18, 12, 9, 3
2. 18, 17, 15, 5, 3
3. 18, 11, 9, 7, 1
4. 13, 12, 10, 10, 6
5. 12, 6, 5, 5, 3
Press Enter to quit

這是一種方法:

var rnd = new Random();

Console.WriteLine(
    string.Join("\n",
        Enumerable
            .Range(1, 5) // returns an IEnumerable<int> containing 1,2,3,4,5.
            .Select(s =>   // for each int in the IEnumerable
                string.Join(",",
                Enumerable
                    .Range(1, 5)
                    .Select(i => rnd.Next(1, 20)) // get a random number.
                    .OrderByDescending(r => r) // order the inner IEnumerable
            )
        )
    )
);

結果(好吧,一種可能的結果,無論如何):

17,17,10,2,1
19,10,10,8,2
17,16,9,3,3
17,16,8,5,1
18,14,13,10,3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM