Merge pull request #236 from swnb/master
add (bitmap) : add bitmap of golang
This commit is contained in:
commit
c38d3bc61c
29
go/45_bitmap/bitmap.go
Normal file
29
go/45_bitmap/bitmap.go
Normal file
@ -0,0 +1,29 @@
|
||||
package bitmap
|
||||
|
||||
// BitMap implement bitmap
|
||||
type BitMap []byte
|
||||
|
||||
// New create BitMap
|
||||
func New(length uint) BitMap {
|
||||
return make([]byte, length/8+1)
|
||||
}
|
||||
|
||||
// Set set value in bitmap
|
||||
func (b BitMap) Set(value uint) {
|
||||
byteIndex := value / 8
|
||||
if byteIndex >= uint(len(b)) {
|
||||
return
|
||||
}
|
||||
bitIndex := value % 8
|
||||
[]byte(b)[byteIndex] |= 1 << bitIndex
|
||||
}
|
||||
|
||||
// Get check whether value exist or not
|
||||
func (b BitMap) Get(value uint) bool {
|
||||
byteIndex := value / 8
|
||||
if byteIndex >= uint(len(b)) {
|
||||
return false
|
||||
}
|
||||
bitIndex := value % 8
|
||||
return []byte(b)[byteIndex]&(1<<bitIndex) != 0
|
||||
}
|
15
go/45_bitmap/bitmap_test.go
Normal file
15
go/45_bitmap/bitmap_test.go
Normal file
@ -0,0 +1,15 @@
|
||||
package bitmap
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBitMap(t *testing.T) {
|
||||
bitMap := New(80)
|
||||
for i := 0; i <= 100; i += 10 {
|
||||
bitMap.Set(uint(i))
|
||||
}
|
||||
for i := 0; i <= 100; i += 10 {
|
||||
t.Log(bitMap.Get(uint(i)))
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user