zoukankan      html  css  js  c++  java
  • 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] + " ");
    }
    ---------------------

    原文:https://blog.csdn.net/u013271384/article/details/51766300

  • 相关阅读:
    bzoj 3226 [Sdoi2008]校门外的区间(线段树)
    bzoj 1513 [POI2006]Tet-Tetris 3D(二维线段树)
    cf293E Close Vertices(树分治+BIT)
    点分治练习:不虚就是要AK
    点分治练习: boatherds
    bzoj 4016 [FJOI2014]最短路径树问题(最短路径树+树分治)
    bzoj 1876 [SDOI2009]SuperGCD(高精度+更相减损)
    464 整数排序Ⅱ
    445 余弦相似度
    488 快乐数
  • 原文地址:https://www.cnblogs.com/jdbn/p/10089753.html
Copyright © 2011-2022 走看看