java随机生成n个不相同的整数

使用java的 java.util.Random

import java.util.Random;

/**
 * 随机生成n个不同的数
 * 
 * @author 张俊峰
 *
 */
public class ArrayRandom {

    /**
     * 随机生成n个不同的数
     * 
     * @param amount
     *            需要的数量
     * @param max
     *            最大值(不含),例:max为100,则100不能取到,范围为0~99;
     * @return 数组
     */
    public static int[] random(int amount, int max) {

        if (amount > max) { // 需要数字总数必须小于数的最大值,以免死循环!
            throw new ArrayStoreException(
                    "The amount of array element must smallar than the maximum value !");
        }
        int[] array = new int[amount];
        for (int i = 0; i < array.length; i++) {
            array[i] = -1; // 初始化数组,避免后面比对时数组内不能含有0。
        }
        Random random = new Random();
        int num;
        amount -= 1; // 数组下标比数组长度小1
        while (amount >= 0) {
            num = random.nextInt(max);
            if (exist(num, array, amount - 1)) {
                continue;
            }
            array[amount] = num;
            amount--;
        }
        return array;
    }

    /**
     * 判断随机的数字是否存在数组中
     * 
     * @param num
     *            随机生成的数
     * @param array
     *            判断的数组
     * @param need
     *            还需要的个数
     * @return 存在true,不存在false
     */
    private static boolean exist(int num, int[] array, int need) {

        for (int i = array.length - 1; i > need; i--) {// 大于need用于减少循环次数,提高效率。
            if (num == array[i]) {
                return true;
            }
        }
        return false;
    }

    /**
     * 随机生成一个数
     * 
     * @param max
     *            最大值(不含)
     * @return 整型数
     */
    public static int random(int max) {

        return random(1, max)[0];
    }
}

使用:

        int[] arr = ArrayRandom.random(20, 100);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " "); 
        }
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值