好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现获取指定个数的不同随机数

两个简单的例子,代码实现如下:

1、随机拆分一个整数

?

1

2

3

4

5

6

7

8

9

10

11

12

13

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、从已知列表中随机选取不同对象 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

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、把一个整数拆分成不等的几份

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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;

}

例子很简单,仅供参考。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/weixin_35971547/article/details/85622745

查看更多关于Java实现获取指定个数的不同随机数的详细内容...

  阅读:8次