java生成指定个数及区间范围的不重复随机数存入数组中

来源:互联网 发布:php api接口开发 编辑:程序博客网 时间:2024/05/14 08:29
//打印数组内容public void print(Integer[] arr) {        if(arr != null) {            for (int i = 0; i < arr.length; i++) {                if(i == 0) {                    System.out.print("[");                }                System.out.print(arr[i]);                if(i == arr.length - 1) {                    System.out.print("]");                } else {                    System.out.print(",");                }            }        } else {            System.out.println("arr is null");        }    }    /**     * 通过指定的多少内的随机数及生成个数及是否从0开始,返回不重复的随机数数组     * @param randomVal --- 多少内的随机数     * @param arrSize  --- 数组长度     * @param startZero  --- 是否从0开始     * @return     * @throws IllegalAccessException     */    public Integer[] random(int randomVal, int arrSize, boolean startZero) throws IllegalAccessException {        if(randomVal < arrSize) {            throw new IllegalAccessException("randomVal can't less than arrSize");        } else if (randomVal <= 0) {            throw new IllegalAccessException("randomVal should more than 0");        }        Integer[] arr = new Integer[arrSize];        for (int i = 0; true;) {            int val = new Random().nextInt(randomVal);            if(!startZero) {                val += 1;            }            boolean hasExist = false;            if(i > 0) {                for(int j = i - 1; j >= 0; j --) {                    if (val == arr[j]) {                        hasExist = true;                        break;                    }                }            }            if(!hasExist) {                arr[i ++] = val;            }            if(i == arrSize) {                break;            }        }        return arr;    }

调用方式

print(random(5, 5, false));   //随机结果的一种 [1,2,5,4,3] print(random(5, 5, true));   //随机结果的一种 [0,4,1,3,2] print(random(100, 5, true));  //随机结果的一种 [45,27,51,99,88]