The method below creates a one-dimensional array of type int of a given size and randomly assigns the value 1 to a given percentage of the array. I don't completely understand the use of nextInt in this example. How is it made sure that in every iteration of the while loop a different index is chosen and not an index that was already chosen in a previous iteration.
import java.util.Random;
...
int[] randomIntArray(int size, double percent) {
int n = (int) (size * percent);
int[] array = new int[size];
Random r = new Random();
while(n > 0) {
int next = r.nextInt(size);
if (array[next] != 0) continue;
array[next] = 1;
n--;
}
return array;
}
Aucun commentaire:
Enregistrer un commentaire