Randomly pick k bits out of n from a Java BitSet
如何从EDCOX1长度为1的Java位集准确地选择EDCOX1×0位,EDCX1 2位开启,其中EDCOX1为3?
示例输入:
示例输出:
选择一个随机数
当
您可以从第一个位扫描到最后一个位,并对设置的位应用水库采样。
该算法具有
如果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private static Random rand = new Random(); public static BitSet chooseBits(BitSet b, int k) { int n = b.cardinality(); int[] indices = new int[n]; // collect indices: for (int i = 0, j = 0; i < n; i++) { j=b.nextSetBit(j); indices[i] =j++; } // create returning set: BitSet ret = new BitSet(b.size()); // choose k bits: for (int i = 0; i<k; i++) { //The first n-i elements are still available. //We choose one: int pick = rand.nextInt(n-i); //We add it to our returning set: ret.set(indices[pick]); //Then we replace it with the current (n-i)th element //so that, when i is incremented, the //first n-i elements are still available: indices[pick] = indices[n-i-1]; } return ret; } |
如何找到所有集合位的
如果约束允许,可以通过以下方式解决任务:
构造一个包含所有设置位索引的
如果