Here's one way to do all of the things you mentioned:
private static boolean arrayContainsInt(int array[], int val, int x) {
for(int i = 0; i < x; i++) {
if(array[i] == val) {
return true;
}
}
return false;
}
public static int[] randomNumbers(int count, int minInclusive, int maxNonInclusive) {
int randoms[] = new int[count];
Random rand = new Random();
int impossibleValue = minInclusive - 1;
for(int i = 0; i < randoms.length; i++) {
randoms[i] = impossibleValue;
}
for(int x = 0; x < count; x++) {
int thisTry = impossibleValue;
while(thisTry == impossibleValue || arrayContainsInt(randoms, thisTry, x)) {
thisTry = (int)(rand.nextFloat() * (float)(maxNonInclusive - minInclusive)) + minInclusive;
}
randoms[x] = thisTry;
}
return randoms;
}
If you're wondering about speed, here are some stats:
randomNumbers(1000, 0, 10000)
==> 16 milliseconds
(1000 random num. from 0->10,000 with no repeats)
randomNumbers(10000, 0, 10000)
==> 207 milliseconds
(Every number from 0->10,000 generated in random order)
The randomNumbers
method is supplied the number of random integers to generate, the minimum value (inclusive), and the maximum value (non-inclusive) and returns an array of randoms given the supplied parameters.
Note: if the count
parameter provided is greater than the value of maxNonInclusive - minInclusive
then it will loop infinitely, simply because you cannot come up with more integers than the range provides.
Also, arrayContainsInt
is sent the x
parameter as value following the maximum index in the array to check because only x
many elements of the array have been populated, so checking the rest is pointless.