How to pick exactly k
bits from a Java BitSet of length m
with n
bits turned on, where k≤n≤m
?
Example input: m=2
If the constraints allow it you can solve the task by:
Construct a List
holding all the set bits indexes. Do Collections#shuffle
on it. Choose the first k
indexes from the shuffled list.
EDIT As per the comments this algorithm can be inefficient if k
is really small, whilst n
is big. Here is an alternative: generate k
random, different numbers in the interval [0, n]
. If in the generation of a number the number is already present in the set of chosen indices, do the chaining approach: that is increase the number by 1 until you get a number that is not yet present in the set. Finally the generated indices are those that you choose amongst the set bits.