[英]how to generate the array contains random number in ascending order using java
我想让数组包含按升序排列的随机数,例如 (1,5,10...100),但不是 (5,1,10...)。 此代码但运行时数字不会升序。 什么错误?
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);}
```
您可以使用Random#ints
方法,该方法返回 stream 的随机 int 值。 假设您想要[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));
如果你想允许重复,你可以省略distinct
要按降序排序,您需要将原始类型装箱到 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.