I am trying to generate a 5 digit int
array in Java and am having trouble on where to start. None of the numbers in the array can be duplicates. I can generate
this generates it in O(number of digits), no inner loops, no shuffling <- this could be expensive if the number of choices gets really big
int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Random random = new Random();
int[] generateId() {
int[] choices = digits.clone();
int[] id = new int[5];
for (int i = 0; i < 5; i++) {
// one less choice to choose from each time
int index = random.nextInt(choices.length - i);
id[i] = choices[index];
// "remove" used item by replacing it with item at end of range
// because that index at the end won't be considered in next round
choices[index] = choices[choices.length - i - 1];
}
return id;
}