Randomly pick k bits out of n from a Java BitSet

后端 未结 4 677
無奈伤痛
無奈伤痛 2021-01-21 08:42

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

4条回答
  •  借酒劲吻你
    2021-01-21 08:57

    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.

提交回复
热议问题