生成随机数方法解析

    xiaoxiao2021-03-25  78

    //冒泡排序 public static void bubbleSort(int[] a) { int temp; for (int i = 0; i < a.length - 1; ++i) { for (int j = a.length - 1; j > i; --j) { if (a[j] < a[j - 1]) { temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; } } } } /** * 随机指定范围内N个不重复的数 * 最简单最基本的方法,两重循环去重 * @param min 指定范围最小值 * @param max 指定范围最大值 * @param n 生成随机数的个数 */ public static int[] randomCommon(int min, int max, int n){ if (n > (max - min + 1) || max < min) {//判断生成的个数不要大于总数,或者max < min return null; } int[] result = new int[n];//最终需要的那个数组 int count = 0;//加个标记,count < n的时候说明生成的数还不够,就继续循环 while(count < n) { //int num = (int) (Math.random() * (max - min)) + min;//生成一个随机数,这样取不到最大值,因为强转int,直接舍去小数了 long aa=Math.round(Math.random() * (max - min));//先四舍五入 int num = (int) (aa) + min;//生成一个随机数 boolean flag = true; for (int j = 0; j < n; j++) {//这个循环就是拿生成的随机数和已经生成的数比较,看看是不是重复了 if(num == result[j]){//num == result[j]就是生成重复了,然后break,继续while循环 flag = false; break; } } if(flag){//如果不重复,存到数组 result[count] = num; count++; } } bubbleSort(result);//排序一下 return result; }
    转载请注明原文地址: https://ju.6miu.com/read-36197.html

    最新回复(0)