Create Array with Unique Value
import java.util.Random;
class Main {
final public static int[] createArrayWithUniqueValues(final int min,
final int max, final int count) {
int numFulfilled = 0;
int[] fulfilled = new int[count];
Random r = new Random();
while (numFulfilled < count) {
int candidate = r.nextInt(max) + min;
if (!contains(fulfilled, numFulfilled, candidate)) {
fulfilled[numFulfilled] = candidate;
numFulfilled++;
}
}
return fulfilled;
}
final public static int[] createAndFillArrayWithUniqueValues(final int min,
final int max) {
int count = max - min + 1;
return createArrayWithUniqueValues(min, max, count);
}
final public static boolean contains(final int[] a, final int candidate) {
return contains(a, a.length, candidate);
}
final private static boolean contains(final int[] a, final int numItems,
final int candidate) {
for (int i = 0; i < numItems; i++) {
if (candidate == a[i])
return true;
}
return false;
}
}
Related examples in the same category