I want to generate a permutation of an array a
and I don't want to use utility functions such as java.util.Collections()
.
The permutations should be randomized and every permutation should be possible to occur - but there is no need for an equally distributed probability.
The following code achieves this - but at poor performance :
// array holding 1,...,n
// initialized somewhere else
int[] a = new int[N];
for (int i = 0; i < a.length ; i++) {
int r = (int) (Math.random() * (i+1));
swap(r,i,a);
}
private static void swap(int j, int k, int[] array){
int temp = array[k];
array[k] = array[j];
array[j] = temp;
}
Question:
Is there any chance of reducing the total number of random numbers used for the generation of a permutation?