java 生成无重复 随机数
生活随笔
收集整理的這篇文章主要介紹了
java 生成无重复 随机数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
一、實現(xiàn)邏輯
? ? ? 1.需要一個固定的數(shù)據(jù)集。
????? ?2.從數(shù)據(jù)集中隨機去除當前索引的數(shù)據(jù),并移除生成。并重復生成多個。
二、編碼
import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Random;import org.slf4j.Logger; import org.slf4j.LoggerFactory;/*** @author liushuaic* @date 2016-08-31 13:49* @desc 隨機生成類* **/ public class RandomUtils {private static Logger logger=LoggerFactory.getLogger(RandomUtils.class);/*** @author liushuaic* @date 2016-08-31 14:17* @desc 隨機不重復的數(shù)據(jù)* */public static int[] randomNumber(int maxNumber,int rtnCount) throws Exception{logger.info("starTime:"+Calendar.getInstance().getTimeInMillis());if(maxNumber == 0){throw new Exception("maxNnumber 不能為 0");}if(rtnCount == 0){throw new Exception("rtnCount 不能為 0");}//logger.info("maxNumber:"+maxNumber+"rtnCount:"+rtnCount);if(rtnCount>maxNumber){throw new ArrayIndexOutOfBoundsException("rtnCount 不能大于 maxNumber");}List<Integer> chacheArray=new ArrayList<Integer>();int[] rtnNumber=new int[rtnCount];for(int i=1;i<=maxNumber;i++){chacheArray.add(Integer.valueOf(i));}for(int j=0;j<rtnCount;j++){int index=new Random().nextInt(chacheArray.size());int val=chacheArray.get(index);rtnNumber[j]=val;chacheArray.remove(index);//logger.info("rtnData--index:"+j+" value:"+val);}logger.info("endTime:"+Calendar.getInstance().getTimeInMillis());return rtnNumber;}public static void main(String[] args) {try {RandomUtils.randomNumber(1000000, 10000);} catch (Exception e) {e.printStackTrace();}}}三、測試結(jié)果?
? ? ? 1.給出100W的長度,取出1W個
? ? ??
? ? ?2.時間長度1.226秒
轉(zhuǎn)載于:https://my.oschina.net/lavedream/blog/740446
總結(jié)
以上是生活随笔為你收集整理的java 生成无重复 随机数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Linux]Linux下安装和配置so
- 下一篇: 李洪强iOS开发之- 实现简单的弹窗