简体   繁体   English

如何使用 java 生成包含升序随机数的数组

[英]how to generate the array contains random number in ascending order using java

I would like to make the array contains random number in ascending order, for example (1,5,10...100), but not (5,1,10...).我想让数组包含按升序排列的随机数,例如 (1,5,10...100),但不是 (5,1,10...)。 this code but when run the number not be ascending.此代码但运行时数字不会升序。 what the error?什么错误?

     Random r=new Random();
     int t=10;
       int a[]=new int[t];
     int count=0;
     int end=0;
     int curr=0;
     while(count<t){
     curr=r.nextInt();
     end=end+curr;
     count++;}
     for(int i=0;i<to;i++){
     a[i]=r.nextInt(10);}
 ```

You can use the Random#ints method which returns a stream of random int values.您可以使用Random#ints方法,该方法返回 stream 的随机 int 值。 Assuming you want 10 random ints from the range [1,100) sorted in ascending order:假设您想要[1,100)范围内的 10 个随机整数按升序排序:

Random r = new Random();
int t    = 10;
int a[]  = r.ints(1, 100).distinct().limit(t).sorted().toArray();
System.out.println(Arrays.toString(a));

you can omit distinct if you want to allow duplicates如果你想允许重复,你可以省略distinct

To sort in descending order you need to box the primitiv types to Integer and use Comparator.reverseOrder() or Collections.reverseOrder() and unbox them after sorting to store them in an int array要按降序排序,您需要将原始类型装箱到 Integer 并使用Comparator.reverseOrder()Collections.reverseOrder()并在排序后将它们拆箱以将它们存储在 int 数组中

int a[]  = r.ints(0, 100)
                .distinct()
                .limit(t)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .mapToInt(Integer::intValue)
                .toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM