Randomly pick k bits out of n from a Java BitSet

后端 未结 4 714
無奈伤痛
無奈伤痛 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 09:13

    If n is much larger than k, you can just pare down the Fisher-Yates shuffle algorithm to stop after you've chosen as many as you need:

    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

提交回复
热议问题