码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-02 19:57:47      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:生成随机数   pre   []   重复   www   ref   add   http   i++   

  • 生成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;
    }
}

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

标签:生成随机数   pre   []   重复   www   ref   add   http   i++   

原文地址:https://www.cnblogs.com/hglibin/p/10462620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!