Randomly pick k bits out of n from a Java BitSet

后端 未结 4 678
無奈伤痛
無奈伤痛 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:56

    You could scan the set from the first bit to the last, and apply reservoir sampling to the bits that are set.

    The algorithm has O(m) time complexity, and requires O(k) memory.

提交回复
热议问题