Java實現獲取指定個數的不同隨機數
更新時間:2019年01月04日 16:30:41 作者:希爾伯特
今天小編就為大家分享一篇關于Java實現獲取指定個數的不同隨機數,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
兩個簡單的例子,代碼實現如下:
1、隨機拆分一個整數
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、把一個整數拆分成不等的幾份
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; }
例子很簡單,僅供參考。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
SpringMVC 中HttpMessageConverter簡介和Http請求415 的問題
本文介紹且記錄如何解決在SpringMVC 中遇到415 Unsupported Media Type 的問題,并且順便介紹Spring MVC的HTTP請求信息轉換器HttpMessageConverter2016-07-07