简体   繁体   中英

Get all Indexes of the set bits in a BitSet

I'm looking for a fast algorithm with gives me all the indexes of the set bits in a BitSet object. This is slow:

BitSet bitSet = ...
Collection<Integer> indexes = new ArrayList<Integer>(bitSet.cardinality());
int nextSetBit = bitSet.nextSetBit(0);
for (int i = 0; i < bitSet.cardinality(); ++i ) {
    indexes.add(nextSetBit);
    nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
}
...

Any help is appreciated!

No need to use bitSet.cardinality() at all:

for (int i = bitSet.nextSetBit(0); i != -1; i = bitSet.nextSetBit(i + 1)) {
    indexes.add(i);
}

As specified in BitSet#nextSetBit(int) javadocs :

//To iterate over the true bits in a BitSet, use the following loop:
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
     // operate on index i here
     if (i == Integer.MAX_VALUE) {
         break; // or (i+1) would overflow
     }
 }

As of Java 8 you can use BitSet's stream() method.

IntStream stream()

Returns a stream of indices for which this BitSet contains a bit in the set state.

Kotlin solution:

val indexes = MutableList<Int>()
var i = bitSet.nextSetBit(0)
while (i != -1) {
    indexes.add(i)
    i = bitSet.nextSetBit(i + 1)
}

bitset.toString() will return all the true bit index
like
10010100
{2, 4, 7}
so you can transfer {2, 4, 7} to java list

Change the loop (you increase the complexity to O(N^2) because you call cardinality() in each loop iteration):

for (int e = bitSet.cardinality(), i = 0; i < e; ++i ) {
    indexes.add(nextSetBit);
    nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM