简体   繁体   中英

How to generate five sets of random numbers

I am trying to generate five sets of a random number in c# order by highest number and comma-separated

I tried using

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

I am getting output only of one set without sorting(Highest to lowest) ie

The random numbers are: 12, 2, 12, 19, 11

The Expected Output should be like this::

  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

Just enhanced your code.

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

Another one...

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

Example output:

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

Here's one way to do it:

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

Result (well, one possible result, anyway):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM