forked from barakmich/bbqvec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counting_bitmap.go
62 lines (54 loc) · 1.08 KB
/
counting_bitmap.go
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package bbq
import (
"fmt"
"github.com/RoaringBitmap/roaring"
)
type CountingBitmap struct {
bms []*roaring.Bitmap
}
func NewCountingBitmap(maxCount int) *CountingBitmap {
return &CountingBitmap{
bms: make([]*roaring.Bitmap, maxCount),
}
}
func (c *CountingBitmap) cardinalities() []int {
cards := make([]int, len(c.bms))
for i, it := range c.bms {
if it == nil {
cards[i] = 0
} else {
cards[i] = int(it.GetCardinality())
}
}
return cards
}
func (c *CountingBitmap) String() string {
return fmt.Sprint(c.cardinalities())
}
func (c *CountingBitmap) Or(in *roaring.Bitmap) {
cur := in
for i := 0; i < len(c.bms); i++ {
if c.bms[i] == nil {
c.bms[i] = roaring.NewBitmap()
}
c.bms[i].Xor(cur)
cur.AndNot(c.bms[i])
c.bms[i].Or(cur)
if cur.GetCardinality() == 0 {
break
}
}
}
// TopK may return more things than intended
func (c *CountingBitmap) TopK(k int) *roaring.Bitmap {
for i := len(c.bms) - 1; i >= 0; i-- {
if c.bms[i] == nil {
continue
}
if i != 0 && int(c.bms[i].GetCardinality()) < k {
continue
}
return c.bms[i]
}
return nil
}