Java案例實現(xiàn)不重復的隨機數(shù)
需求:獲得十個1-20的隨機數(shù),要求隨機數(shù)不能重復,存儲到集合中并遍歷
分析:
- 1.創(chuàng)建Set集合對象,可以使用
HashSet
也可以使用TreeSet
,區(qū)別在于TreeSet是排序后的 - 2.創(chuàng)建隨機數(shù)對象,獲取一個隨機數(shù)
- 3.判斷集合長度是否大于10,是停止生成、存儲并遍歷
- 否:繼續(xù)生成直到長度大于10停止生成、存儲并遍歷
- 4.輸出
代碼:
public class SetDemo { ? public static void main(String[] args) { ? ? ? //創(chuàng)建Set集合對像 ? ? ? Set<Integer> s=new TreeSet<Integer>(); ? ? ? //創(chuàng)建隨機數(shù)對象 ? ? ? Random r=new Random(); ? ? ? while(s.size()<10){ ? ? ? ? ? int num= r.nextInt(20)+1; ? ? ? ? ? s.add(num); ? ? ? } ? ? ? for (Integer i:s){ ? ? ? ? ? System.out.println(i); ? ? ? } ? } } ?
補充:
通過單個數(shù)組簡易實現(xiàn)不重復隨機數(shù)生成,先上源碼。
/** * 獲取隨機數(shù)組 * @param 源數(shù)組 ?* @param size 目標數(shù)組大小 ?* @return 隨機數(shù)組 ?*/ public static int[] getRandomRes(int[] source,int size){ ? ? if (source == null && size > source.length) { ? ? ? ? return; ? ? } ? ? int[] result = new int[size]; ? ? Random random = new Random(); ? ? for (int i = 0; i < size; i++) { ? ? ? ? int randomIndex = random.nextInt(source.length - 1 - i); ? ? ? ? int randomRes = source[randomIndex]; ? ? ? ? result[i] = randomRes; ? ? ? ? int temp = source[randomIndex]; ? ? ? ? source[randomIndex] = source[source.length - 1 - i]; ? ? ? ? source[source.length - 1 - i] = temp; ? ? } ? ? return result; }
下面看圖解,數(shù)字為數(shù)組的index。
黑色數(shù)字表示能隨機到的數(shù),紅色代表不能隨機到數(shù)。
因此只能隨機到index:0~4的數(shù),假設是2,然后將2與index5互換位置。
此時結果result[] = {2}
繼續(xù)循環(huán)
從前index:0~3中循環(huán),假設取出index0
,與index4
互換,此時結果為result = {2,0}
,依次類推。
優(yōu)點:簡單快捷
缺點:每次無法取到最后一個數(shù)。
不斷隨機,使用Set去重
/** *生成隨機數(shù)組 *@param size 目標數(shù)組大小 *@param max 目標數(shù)最大值 */ public Set<Integer> getRandomSet(int size,int max){ ? ? Random random= new Random(); ? ? Set<Integer> result= new LinkedHashSet<Integer>(); ? ? while (generated.size() < size) ? ? { ? ? ? ? Integer next = rng.nextInt(max) + 1; ? ? ? ? generated.add(next); ? ? } }
此處使用LinkedHashSet
保證插入順序與結果相同。
到此這篇關于Java案例實現(xiàn)不重復的隨機數(shù)的文章就介紹到這了,更多相關Java不重復隨機數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JetBrains IntelliJ IDEA 配置優(yōu)化技巧
這篇文章主要介紹了JetBrains IntelliJ IDEA 配置優(yōu)化技巧,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12java逐行讀取文件(讀取文件每一行、按行讀取文件)附帶詳細代碼
這篇文章主要給大家介紹了關于java逐行讀取文件(讀取文件每一行、按行讀取文件)的相關資料,讀取文件是我們在日常工作中經(jīng)常遇到的一個需求,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-09-09java為什么使用BlockingQueue解決競態(tài)條件問題面試精講
這篇文章主要為大家介紹了java為什么使用BlockingQueue解決競態(tài)條件問題面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10Java面試synchronized偏向鎖后hashcode存址
這篇文章主要為大家介紹了Java面試中synchronized偏向鎖后hashcode存址詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05SpringBoot整合Dubbo框架,實現(xiàn)RPC服務遠程調用
Dubbo是一款高性能、輕量級的開源Java RPC框架,它提供了三大核心能力:面向接口的遠程方法調用,智能容錯和負載均衡,以及服務自動注冊和發(fā)現(xiàn)。今天就來看下SpringBoot整合Dubbo框架的步驟2021-06-06