I'm currently looking for a better way, so choose x unique ints from the range of n int. This would be like doing Random.nextInt(range) several times, except that it should never select the same int twice. If this happens, then x > n then the result will contain only n ints
I tried to do it myself, and currently I have done it based on Shuffle Fisher / Yates:
private static final Random R = new Random(); public static int[] distinctRandoms(int nb, int max) { int[] all = new int[max]; for (int i = 0; i < all.length; i++) { all[i] = i; } if (max <= nb) { return all; } int index; int[] result = new int[nb]; for (int j = 0, k = all.length - 1; k > 0 && j < nb; k--, j++) { index = R.nextInt(k + 1); result[j] = all[index];
This works, and the performance seems good, but I can't help but think that there still needs to be an even more efficient way to do this, and that I am inventing the wheel. I was thinking of doing something differently if nb > (max / 2) (delete elements, not select elements), but since you cannot trim the array in java, you still copy all the elements you need . This method is expensive if nb = max-1
Is there a built-in way to randomly select individual ints in java?
Change 1:
What I mean is time-efficient. I want it to be fast. I will mainly work with small sets of random ones.
Edit 2:
I tried using shuffle, but it is much more expensive in terms of time due to the creation of the entire additional object.
public static Integer[] distinctRandoms2(int nb, int max) { ArrayList<Integer> all = new ArrayList<Integer>(max); for (int i = 0; i < max; i++) { all.add(i); } if (max <= nb) { return all.toArray(new Integer[max]); } Collections.shuffle(all); return all.subList(0, nb).toArray(new Integer[nb]); }
java random
Crystals
source share