练习题:Java随机在某个区间中生成n个随机数并升序排列,并把其余位置补0

数组版

int min = 1, max = 10, count = 5,n;
int[] array = new int[min+max];
do {
    n = new Random().nextInt(max)%(max-min+1) + min;
    if (array[n] == 0) {
        array[n] = n;
        count--;
    }
} while (count > 0);
for (int i = min; i <= max; i++) {
    System.out.println(array[i]);
}

2015-11-26_111602

List版

// 最小数
int min = 1;
// 最大数
int max = 10;
// 几率
int per = (int) Math.round(max * 0.5);

Random random = new Random();
List<Integer> countList = new ArrayList<Integer>();
List<Integer> countMaxList = new ArrayList<Integer>();
int x = 0;
int count = 0;
// 加倍生成,以防止生成随机总数不够
for (int i = 0; i < max + max; i++) {
    x = random.nextInt(max) + min;
    if (count == per) break;
    if (!countList.contains(x)) {
        countList.add(x);
        count++;
    }
}
Collections.sort(countList);
System.out.println("=======随机从" + min + "到" + max + ",生成" + per + "个不重复的升序随机数=======");
for (Integer i : countList) {
    System.out.println(i);
}
// 先计算随机数前部分
if (countList.get(0) != 1) {
    for (int i = 1; i < countList.get(0); i++) {
        countMaxList.add(0);
    }
}
// 开始计算随机数
for (int i = 0; i < countList.size(); i++) {
    countMaxList.add(countList.get(i));
    // 如果是最后一个就结束循环
    if (i == countList.size() - 1) break;
    for (int j = countList.get(i) + 1; j < countList.get(i + 1); j++) {
        countMaxList.add(0);
    }
}
// 计算随机数后部分
if (countList.get(countList.size() - 1) != max) {
    for (int i = countList.get(countList.size() - 1) + 1; i <= max; i++) {
        countMaxList.add(0);
    }
}
countList.clear();
System.out.println("=======除随机生成" + per + "个随机数外,其余位置依次按照升序补0填满" + max + "位数=======");
for (Integer i : countMaxList) {
    System.out.println(i);
}

执行效果截图如下:
2015-11-25_155451

发表评论