随机从Java BitSet中挑选k位了n个Java、BitSet

2023-09-11 02:33:56 作者:果冻小布丁

如何挑选究竟 K 位从的长度 M Java的位集合与 N 位打开,其中k≤n≤m

How to pick exactly k bits from a Java BitSet of length m with n bits turned on, where k≤n≤m?

例输入: M = 20,N = 11

Example input: m=20, n=11

输出示例: K = 3

Example output: k=3

选择一个随机数0≤I≤M-1 。如果它是打开输入和未开启的输出,打开它的输出,直到 K 位输出开启。

Choose a random number 0≤ i ≤ m-1.if it's turned on on the input and not turned on on the output, turn it on in the output, until k bits are turned on in the output.

此方法失败时, N M 小得多。任何其他的想法?

This approach fails when n is much smaller than m. Any other ideas?

推荐答案

您可以扫描一组从第一位到最后,并应用的水库取样到设置的位。

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

该算法 O(M)时间复杂度,并要求 O(K)内存

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