不重复的随机数JAVA、C#

计算速度较快,10000个不重复的随机数一秒内肯定能出来,只要数据给的不过分,都行

JAVA语言

public static void main(String[] args) {
        Random ra = new Random();
        List<Integer> list=new ArrayList<Integer>();
        //范围1-
        int scope=10;
        //需求长度
        int count=10;
        if(count>scope){
            System.exit(0);
        }
        for (;;) {
            int ran=ra.nextInt(scope)+1;
            if(!list.contains(ran)){
                list.add(ran);
                if(list.size()==count){
                    break;
                }
            }
        }
        for (Integer integer : list) {
            System.out.print(integer+",");
        }
    }

C#语言

 static void Main(string[] args)
        {
            Random ra = new Random();
            List<Int32> list = new List<Int32>();
            //范围1-
            int scope = 10;
            //需求长度
            int count = 10;
            if (count > scope)
            {
                return;
            }
            for (; ; )
            {
                int ran = ra.Next(scope) + 1;
                if (!list.Contains(ran))
                {
                    list.Add(ran);
                    if (list.Count() == count)
                    {
                        break;
                    }
                }
            }
            foreach (var item in list)
            {
                Console.Write(item+",");
            }
        }

猜你喜欢

转载自blog.csdn.net/feng8403000/article/details/106495426