Generate N random and unique numbers within a range

后端 未结 7 2044
不知归路
不知归路 2020-11-27 07:50

What is an efficient way of generating N unique numbers within a given range using C#? For example, generate 6 unique numbers between 1 and 50. A lazy way would be to simply

7条回答
  •  悲&欢浪女
    2020-11-27 08:16

    generate unique random nos from 1 to 40 :

    output confirmed :

    class Program
    
    {
        static int[] a = new int[40];
        static Random r = new Random();
        static bool b;
        static void Main(string[] args)
        {
            int t;
            for (int i = 0; i < 20; i++)
            {
            lab:  t = r.Next(1, 40);
                for(int j=0;j<20;j++)
                {
    
                    if (a[j] == t)
                    {
                        goto lab;
                    }
                }
    
                a[i] = t;
                Console.WriteLine(a[i]);
    
    
    
            }
            Console.Read();
        }
    
    
    }
    

    sample output :

    7 38 14 18 13 29 28 26 22 8 24 19 35 39 33 32 20 2 15 37

提交回复
热议问题