If a nlot more than kthat, you can simply hide the Shuffle Fisher-Yates algorithm to stop after you choose as many as you need:
private static Random rand = new Random();
public static BitSet chooseBits(BitSet b, int k) {
int n = b.cardinality();
int[] indices = new int[n];
for (int i = 0, j = 0; i < n; i++) {
j=b.nextSetBit(j);
indices[i] =j++;
}
BitSet ret = new BitSet(b.size());
for (int i = 0; i<k; i++) {
int pick = rand.nextInt(n-i);
ret.set(indices[pick]);
indices[pick] = indices[n-i-1];
}
return ret;
}
source
share