兩個簡單的例子,代碼實現如下:
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;}
例子很簡單,僅供參考。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選