Java實現(xiàn)獲取指定個數(shù)的不同隨機(jī)數(shù)
兩個簡單的例子,代碼實現(xiàn)如下:
1、隨機(jī)拆分一個整數(shù)
public static List<Integer> randomList(int n){
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int i = 0;
while (i < n) {
int num = rand.nextInt(n);
if (!list.contains(num)) {
list.add(num);
i++;
}
}
return list;
}
2、從已知列表中隨機(jī)選取不同對象
public static List<Integer> randomList(int n,int size) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int i = 1;
while (i <= n) {
int num = rand.nextInt(size-1) + 1;
if (!list.contains(num)) {
list.add(num);
i++;
}
}
return list;
}
3、把一個整數(shù)拆分成不等的幾份
public static List<Integer> randomList(int n, int m){
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int temp = m;
for(int i = 0, j; i < n-1; i++){
j = rand.nextInt(temp-1) + 1;
temp -= j;
list.add(j);
if (temp == 1){
break;
}
}
list.add(temp);
return list;
}
例子很簡單,僅供參考。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
SpringBoot整合Mybatis實現(xiàn)多數(shù)據(jù)源配置與跨數(shù)據(jù)源事務(wù)實例
開發(fā)中經(jīng)常有這樣的需要: 讀寫分離。微服務(wù)環(huán)境下可以實現(xiàn)一個服務(wù)讀取一個數(shù)據(jù)庫,另一個服務(wù)寫庫。但是在實際應(yīng)用中有時也需要在一個服務(wù)中讀寫不同的數(shù)據(jù)庫??梢栽谝粋€SpringBoot單體項目中配置多個數(shù)據(jù)源解決讀寫庫分離2022-11-11
JPA中@JoinColumn的name和referencedColumnName屬性的區(qū)別及說明
這篇文章主要介紹了JPA中@JoinColumn的name和referencedColumnName屬性的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Spring Boot 參數(shù)校驗的具體實現(xiàn)方式
這篇文章主要介紹了Spring Boot 參數(shù)校驗的具體實現(xiàn)方式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06
java Unicode和UTF-8之間轉(zhuǎn)換實例
這篇文章主要介紹了java Unicode和UTF-8之間轉(zhuǎn)換實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Java Web Filter 過濾器學(xué)習(xí)教程(推薦)
Filter也稱之為過濾器,它是Servlet技術(shù)中最激動人心的技術(shù).這篇文章主要介紹了Java Web Filter 過濾器學(xué)習(xí)教程的相關(guān)資料,需要的朋友可以參考下2016-05-05

