国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Java > 正文

Java實現(xiàn)獲取指定個數(shù)的不同隨機數(shù)

2024-07-14 08:43:28
字體:
來源:轉載
供稿:網友

兩個簡單的例子,代碼實現(xiàn)如下:

1、隨機拆分一個整數(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、從已知列表中隨機選取不同對象 

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;}

例子很簡單,僅供參考。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 黄大仙区| 广安市| 鄄城县| 行唐县| 保定市| 大厂| 巍山| 安阳市| 马关县| 赤峰市| 上虞市| 上栗县| 冕宁县| 西林县| 扎囊县| 福贡县| 当阳市| 太保市| 隆安县| 吕梁市| 盐源县| 阜平县| 深泽县| 离岛区| 永川市| 房山区| 兰溪市| 宁乡县| 泸定县| 新源县| 乌兰察布市| 涪陵区| 阜南县| 英德市| 东乡族自治县| 七台河市| 博乐市| 芮城县| 阳春市| 慈溪市| 奉新县|