Generating multiple random numbers

后端 未结 5 1594
时光说笑
时光说笑 2021-02-15 11:09

I want to generate 25 unique random numbers and list them in a console. The numbers should be atleast 10 characters long. Any easy way to do that?

5条回答
  •  醉梦人生
    2021-02-15 11:54

    One simple way is this:

    class Test
    {
        private static void Main()
        {
            Random rand = new Random();
    
            for (int i = 0; i < 25; ++i)
            {
                Console.WriteLine(rand.Next(1000000000, int.MaxValue));
            }
        }
    }
    

    This will ensure that the numbers are always 10 characters (digits) long. They will not necessarily be unique however. If you want them to definitely be unique, you'll have to do something like this:

    class Test
    {
        private static void Main()
        {
            Random rand = new Random();
    
            var generatedSoFar = new HashSet();
            for (int i = 0; i < 25; ++i)
            {
                int newRand;
                do
                {
                    newRand = rand.Next(1000000000, int.MaxValue);
                } while (generatedSoFar.Contains(newRand)); // generate a new random number until we get to one we haven't generated before
    
                generatedSoFar.Add(newRand);
    
                Console.WriteLine(newRand);
            }
        }
    }
    

    If you want to be able to have more than ten digits, you generate the number of digits randomly between 10 and your max number of digits. Then generate each digit (or group of digits) randomly in a StringBuilder or List. You can use the same HashSet method I used above to ensure uniqueness.

提交回复
热议问题