A simple way to get N
shuffled elements from the array is as follows:
- Pick a random element
r
. - Add element
r
to the output. - Move the last element of the array to the position of
r
and shrink the array size by 1. - Repeat
N
times.
In code:
public static int[] shuffle(int[] array, int N) {
int[] result = new int[N];
int length = array.length;
Random gen = new Random();
for (int i = 0; i < N; i++) {
int r = gen.nextInt(length);
result[i] = array[r];
array[r] = array[length-1];
length--;
}
return result;
}
This algorithm has the advantage over FY that it only computes the first N
elements of the shuffled array, rather than shuffling the whole array.
Your optimized algorithm is not optimal for two reasons:
- The first
N
elements are never shuffled. For instance, element 0 can never appear at position 1 in the shuffled array. - You're still doing a lot of work. If
N=10
and the total array length is1000000
, you're still computing about1000000
random values, while you only need10
.