3

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);}
 ```
1
  • Maybe something like this? ideone.com/vtKJHf where you save the previously generated value to be used to generate the next one, only downside is, when random value generated is pretty high, as seen in the link... Commented Dec 1, 2020 at 19:24

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

@Maymunah Edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.