Skip to content

Commit 64dafb7

Browse files
committed
Implement Count for bitArray and sparseBitArray
1 parent d95ee5d commit 64dafb7

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

bitarray/bitarray.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,15 @@ func (ba *bitArray) ClearBit(k uint64) error {
202202
return nil
203203
}
204204

205+
// Count returns the number of set bits in this array.
206+
func (ba *bitArray) Count() uint64 {
207+
count := 0
208+
for _, block := range ba.blocks {
209+
count += bits.OnesCount64(uint64(block))
210+
}
211+
return uint64(count)
212+
}
213+
205214
// Or will bitwise or two bit arrays and return a new bit array
206215
// representing the result.
207216
func (ba *bitArray) Or(other BitArray) BitArray {

bitarray/sparse_bitarray.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ limitations under the License.
1616

1717
package bitarray
1818

19-
import "sort"
19+
import (
20+
"math/bits"
21+
"sort"
22+
)
2023

2124
// uintSlice is an alias for a slice of ints. Len, Swap, and Less
2225
// are exported to fulfill an interface needed for the search
@@ -243,6 +246,15 @@ func (sba *sparseBitArray) Equals(other BitArray) bool {
243246
return true
244247
}
245248

249+
// Count returns the number of set bits in this array.
250+
func (sba *sparseBitArray) Count() uint64 {
251+
count := 0
252+
for _, block := range sba.blocks {
253+
count += bits.OnesCount64(uint64(block))
254+
}
255+
return uint64(count)
256+
}
257+
246258
// Or will perform a bitwise or operation with the provided bitarray and
247259
// return a new result bitarray.
248260
func (sba *sparseBitArray) Or(other BitArray) BitArray {

0 commit comments

Comments
 (0)