生成n个不同的随机数,且随机数区间为[0,n)

  • 生成n个不同的随机数,且随机数区间为[0,n)
package cn.hgnulb.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TestRandom {
    public static void main(String[] args) {
        System.out.println(getDiffNO(10));
    }

    /**
     * 生成n个不同的随机数,且随机数区间为[0,n)
     * 
     * @param n 生成随机数的个数
     * @return 返回生成 [0-n) 个不重复的随机数,用 list 来保存这些随机数
     */
    public static List<Integer> getDiffNO(int n) {
        // list 用来保存这些随机数
        List<Integer> list = new ArrayList<Integer>();
        Random rand = new Random();
        boolean[] bool = new boolean[n];
        int num = 0;
        for (int i = 0; i < n; i++) {
            do {
                // 如果产生的数相同则继续循环
                num = rand.nextInt(n);
            } while (bool[num]);
            bool[num] = true;
            list.add(num);
        }
        return list;
    }
}

猜你喜欢

转载自www.cnblogs.com/hglibin/p/10462620.html