int[] getRandoms(int[] ranges, int n, int[] excepts) {
int min = ranges[0];
int max = ranges[1];
int[] results = new int[n];
for (int i = 0; i < n; i++) {
int randomValue = new Random().nextInt(max - min + 1) + min;
if (ArrayUtils.contains(results, randomValue) || ArrayUtils.contains(excepts, randomValue)) {
i--;
} else {
results[i] = randomValue;
}
}
return results;
}
clase util
public static class ArrayUtils {
public static boolean contains(int[] array, int elem) {
return getArrayIndex(array, elem) != -1;
}
/** Return the index of {@code needle} in the {@code array}, or else {@code -1} */
public static int getArrayIndex(int[] array, int needle) {
if (array == null) {
return -1;
}
for (int i = 0; i < array.length; ++i) {
if (array[i] == needle) {
return i;
}
}
return -1;
}
}
usando
int[] randomPositions = getRandoms(new int[]{0,list.size()-1}, 3, new int[]{0,1});
será al azar 3 elementos de la lista, salvo el punto 0 y el punto 1
¡De hecho, es una muy buena idea! ¡Muchas gracias! – Yokhen
protección utilizable de IndexOutOfBoundsException: return n> copy.size()? copy.subList (0, copy.size()): copy.subList (0, n); – pawegio
Mezclar toda la lista cuando solo necesita 3 elementos es un desperdicio de listas grandes. – Eyal