vendredi 26 février 2021

How to generate an array of pseudo-random, unique, sorted integers without using an if statement?

I need to create an array of pseudo-random unique integers that are already in an ascending order without using an if statement. For example:

[3,5,7,12]

So far I was able to come up with this code, which repeats some numbers and doesn't put the integers in sorted order.

int[] arr = new int[r.nextInt(10)];
for (int i = 0; i < arr.length; i++) {
    int randInt = r.nextInt(arr.length);
    arr[i] = randInt;
}

What is the best way to work around this? Note: I have to not use the ArrayList and sort method.

Aucun commentaire:

Enregistrer un commentaire