Here are three approachs:
1)
Your own approach only with a modified inner loop that goes through all previous random numbers from 0 to i-1
and checks for duplicates. If a duplicate is found just force a generation of a new random number by decrementing the index of the outer loop --i
public static int[] generatePicks3(int size, int lowValue, int highValue, long seed) {
Random rand = new Random(seed);
int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt((highValue - lowValue) + 1) + lowValue;
for (int j = 0; j < i; j++) {
if (arr[j] == arr[i]) {
--i;
}
}
}
Arrays.sort(arr);
return arr;
}
2)
Using IntStream(lowValue, highValue+1)
and Collections.shuffle(List<?>, rand)
Generate all numbers between lowValue
and highValue
collect them to list, shuffle the list and get the first n
elements, where n = size
public static int[] generatePicks2(int size, int lowValue, int highValue, long seed) {
Random rand = new Random(seed);
List<Integer> list = IntStream.range(lowValue, highValue+1).boxed().collect(Collectors.toList());
Collections.shuffle(list, rand);
return list.stream().limit(size).mapToInt(Integer::intValue).sorted().toArray();
}
3)
The simplest and shortest way using Random.ints()
: generate an infinite stream of random numbers between lowValue
and highValue
make them unique by applying distinct()
and limit the stream to the desiered size
.
public static int[] generatePicks(int size, int lowValue, int highValue, long seed) {
Random rand = new Random(seed);
return rand.ints(lowValue, highValue).distinct().limit(size).sorted().toArray();
}