简体   繁体   中英

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...). 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. Assuming you want 10 random ints from the range [1,100) sorted in ascending order:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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