java 随机生成不重复的随机数

生成随机不重复的随机数

1. 第一种
/**
     * 随机生成不重复的随机数
     * @param min           最小值
     * @param max           最大值
     * @param size          个数
     * @return
     */
    public static List<Integer> getRandom(int min,int max,int size){
        List<Integer> nums = null;
        if (size>(max-min) || size==0 || min>=max){
            return nums;
        }
        nums = new ArrayList<Integer>();
        Random random = new Random();
        int code;

        A:for (;;) {
            code = (random.nextInt(max)+min);
            for (int c : nums){
                if (c==code){
                    continue A;
                }
            }
            nums.add(code);
            if (nums.size()==size) {
                break;
            }
        }
        return nums;
    }

2.第二种
 /**
     * 获取指定范围内指定个数的随机不重复数组
     * @param min
     * @param max
     * @param n
     * @return
     */
    public static int[] randomNum(int min, int max, int n){
        Set<Integer> set = new HashSet<Integer>();
        int[] result = new int[n];
        for (; true;) {
            // 调用Math.random()方法
            Double rd = Math.random()*1000.0 ;
            int vl = rd.intValue()%n+min ;
            if (vl> max || vl<min)
                continue;

            // 将不同的数存入HashSet中
            set.add(vl);
            // 如果存入的数小于指定生成的个数,则调用递归再生成剩余个数的随机数,如此循环,直到达到指定大小
            if (set.size() >= n) {
                break;
            }
        }
        int i = 0;
        for (int a : set) {
            result[i] = a;
            i++;
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值