欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Golang中Bit數(shù)組的實現(xiàn)方式

 更新時間:2021年04月30日 08:39:02   作者:天易獨尊  
這篇文章主要介紹了Golang中Bit數(shù)組的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

Go語言里的集合一般會用map[T]bool這種形式來表示,T代表元素類型。集合用map類型來表示雖然非常靈活,但我們可以以一種更好的形式來表示它。

例如在數(shù)據(jù)流分析領域,集合元素通常是一個非負整數(shù),集合會包含很多元素,并且集合會經常進行并集、交集操作,這種情況下,bit數(shù)組會比map表現(xiàn)更加理想。

一個bit數(shù)組通常會用一個無符號數(shù)或者稱之為“字”的slice來表示,每一個元素的每一位都表示集合里的一個值。當集合的第i位被設置時,我們才說這個集合包含元素i。

下面的這個程序展示了一個簡單的bit數(shù)組類型,并且實現(xiàn)了三個函數(shù)來對這個bit數(shù)組來進行操作:

package main
import (
	"bytes"
	"fmt"
)
// An IntSet is a set of small non-negative integers.
// Its zero value represents the empty set.
type IntSet struct {
	words []uint
}
const (
	bitNum = (32 << (^uint(0) >> 63)) //根據(jù)平臺自動判斷決定是32還是64
)
// Has reports whether the set contains the non-negative value x.
func (s *IntSet) Has(x int) bool {
	word, bit := x/bitNum, uint(x%bitNum)
	return word < len(s.words) && s.words[word]&(1<<bit) != 0
}
// Add adds the non-negative value x to the set.
func (s *IntSet) Add(x int) {
	word, bit := x/bitNum, uint(x%bitNum)
	for word >= len(s.words) {
		s.words = append(s.words, 0)
	}
	s.words[word] |= 1 << bit
}
//A與B的交集,合并A與B
// UnionWith sets s to the union of s and t.
func (s *IntSet) UnionWith(t *IntSet) {
	for i, tword := range t.words {
		if i < len(s.words) {
			s.words[i] |= tword
		} else {
			s.words = append(s.words, tword)
		}
	}
}

因為每一個字都有64個二進制位,所以為了定位x的bit位,我們用了x/64的商作為字的下標,并且用x%64得到的值作為這個字內的bit的所在位置。

例如,對于數(shù)字1,將其加入比特數(shù)組:

func (s *IntSet) Add(x int) {
 word, bit := x/bitNum, uint(x%bitNum) //0, 1 := 1/64, uint(1%64)
 for word >= len(s.words) { // 條件不滿足
  s.words = append(s.words, 0)
 }
 s.words[word] |= 1 << bit // s.words[0] |= 1 << 1
}
// 把1存入后,words數(shù)組變?yōu)榱薣]uint64{2}

同理,假如我們再將66加入比特數(shù)組:

func (s *IntSet) Add(x int) {
 word, bit := x/bitNum, uint(x%bitNum) //1, 2 := 66/64, uint(66%64)
 for word >= len(s.words) { // 條件滿足
  s.words = append(s.words, 0) // 此時s.words = []uint64{2, 0}
 }
 s.words[word] |= 1 << bit // s.words[1] |= 1 << 2
}
// 繼續(xù)把66存入后,words數(shù)組變?yōu)榱薣]uint64{2, 4}

所以,對于words,每個元素可存儲的值有64個,每超過64個則進位,即添加一個元素。(注意,0也占了一位,所以64才要進位,第一個元素可存儲0-63)。

所以,對于words中的一個元素,要轉換為具體的值時:首先取到其位置i,用 64 * i 作為已進位數(shù)(類似于每10位要進位), 然后將這個元素轉換為二進制數(shù),從右往左數(shù),第多少位為1則表示相應的有這個值,用這個位數(shù) x+64 *i 即為我們存入的值。

相應的,可有如下String()函數(shù)

// String returns the set as a string of the form "{1 2 3}".
func (s *IntSet) String() string {
 var buf bytes.Buffer
 buf.WriteByte('{')
 for i, word := range s.words {
  if word == 0 {
   continue
  }
  for j := 0; j < bitNum; j++ {
   if word&(1<<uint(j)) != 0 {
    if buf.Len() > len("{") {
     buf.WriteByte(' ')
    }
    fmt.Fprintf(&buf, "%d", bitNum*i+j)
   }
  }
 }
 buf.WriteByte('}')
 return buf.String()
}

例如,前面存入了1和66后,轉換過程為:

// []uint64{2 4}
// 對于2: 1 << 1 = 2; 所以 x = 0 * 64 + 1 
// 對于4: 1 << 2 = 4; 所以 x = 1 * 64 + 2
// 所以轉換為String為{1 66}

實現(xiàn)比特數(shù)組的其他方法函數(shù)

func (s *IntSet) Len() int {
	var len int
	for _, word := range s.words {
		for j := 0; j < bitNum; j++ {
			if word&(1<<uint(j)) != 0 {
				len++
			}
		}
	}
	return len
}
func (s *IntSet) Remove(x int) {
	word, bit := x/bitNum, uint(x%bitNum)
	if s.Has(x) {
		s.words[word] ^= 1 << bit
	}
}
func (s *IntSet) Clear() {
	s.words = append([]uint{})
}
func (s *IntSet) Copy() *IntSet {
	intSet := &IntSet{
		words: []uint{},
	}
	for _, value := range s.words {
		intSet.words = append(intSet.words, value)
	}
	return intSet
}
func (s *IntSet) AddAll(args ...int) {
	for _, x := range args {
		s.Add(x)
	}
}
//A與B的并集,A與B中均出現(xiàn)
func (s *IntSet) IntersectWith(t *IntSet) {
	for i, tword := range t.words {
		if i >= len(s.words) {
			continue
		}
		s.words[i] &= tword
	}
}
//A與B的差集,元素出現(xiàn)在A未出現(xiàn)在B
func (s *IntSet) DifferenceWith(t *IntSet) {
	t1 := t.Copy() //為了不改變傳參t,拷貝一份
	t1.IntersectWith(s)
	for i, tword := range t1.words {
		if i < len(s.words) {
			s.words[i] ^= tword
		}
	}
}
//A與B的并差集,元素出現(xiàn)在A沒有出現(xiàn)在B,或出現(xiàn)在B沒有出現(xiàn)在A
func (s *IntSet) SymmetricDifference(t *IntSet) {
	for i, tword := range t.words {
		if i < len(s.words) {
			s.words[i] ^= tword
		} else {
			s.words = append(s.words, tword)
		}
	}
}
//獲取比特數(shù)組中的所有元素的slice集合
func (s *IntSet) Elems() []int {
	var elems []int
	for i, word := range s.words {
		for j := 0; j < bitNum; j++ {
			if word&(1<<uint(j)) != 0 {
				elems = append(elems, bitNum*i+j)
			}
		}
	}
	return elems
}

至此,比特數(shù)組的常用方法函數(shù)都已實現(xiàn),現(xiàn)在可以來使用它。

func main() {
	var x, y IntSet
	x.Add(1)
	x.Add(144)
	x.Add(9)
	fmt.Println("x:", x.String()) // "{1 9 144}"
	y.Add(9)
	y.Add(42)
	fmt.Println("y:", y.String()) // "{9 42}"
	x.UnionWith(&y)
	fmt.Println("x unionWith y:", x.String())         // "{1 9 42 144}"
	fmt.Println("x has 9,123:", x.Has(9), x.Has(123)) // "true false"
	fmt.Println("x len:", x.Len())                    //4
	fmt.Println("y len:", y.Len())                    //2
	x.Remove(42)
	fmt.Println("x after Remove 42:", x.String()) //{1 9 144}
	z := x.Copy()
	fmt.Println("z copy from x:", z.String()) //{1 9 144}
	x.Clear()
	fmt.Println("clear x:", x.String()) //{}
	x.AddAll(1, 2, 9)
	fmt.Println("x addAll 1,2,9:", x.String()) //{1 2 9}
	x.IntersectWith(&y)
	fmt.Println("x intersectWith y:", x.String()) //{9}
	x.AddAll(1, 2)
	fmt.Println("x addAll 1,2:", x.String()) //{1 2 9}
	x.DifferenceWith(&y)
	fmt.Println("x differenceWith y:", x.String()) //{1 2}
	x.AddAll(9, 144)
	fmt.Println("x addAll 9,144:", x.String()) //{1 2 9 144}
	x.SymmetricDifference(&y)
	fmt.Println("x symmetricDifference y:", x.String()) //{1 2 42 144}
	for _, value := range x.Elems() {
		fmt.Print(value, " ") //1 2 42 144
	}
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關文章

  • Golang編寫自定義IP限流中間件的方法詳解

    Golang編寫自定義IP限流中間件的方法詳解

    這篇文章給大家詳細的介紹了Golang編寫自定義IP限流中間件的方法,文章通過代碼實例介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下
    2023-09-09
  • golang基于Mutex實現(xiàn)可重入鎖

    golang基于Mutex實現(xiàn)可重入鎖

    鎖可重入也就是當前已經獲取到鎖的goroutine繼續(xù)調用Lock方法獲取鎖,Go標準庫中提供了sync.Mutex實現(xiàn)了排他鎖,但并不是可重入的,所以本文給大家介紹了golang基于Mutex實現(xiàn)可重入鎖,文中有詳細的代碼示例,需要的朋友可以參考下
    2024-03-03
  • Golang在整潔架構基礎上實現(xiàn)事務操作

    Golang在整潔架構基礎上實現(xiàn)事務操作

    這篇文章在 go-kratos 官方的 layout 項目的整潔架構基礎上,實現(xiàn)優(yōu)雅的數(shù)據(jù)庫事務操作,需要的朋友可以參考下
    2024-08-08
  • go常用指令之go?mod詳解

    go常用指令之go?mod詳解

    當go命令運行時,它查找當前目錄然后查找相繼的父目錄來找出 go.mod,下面這篇文章主要給大家介紹了關于go常用指令之go?mod的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-08-08
  • Golang中的map操作方法詳解

    Golang中的map操作方法詳解

    這篇文章主要給大家介紹了關于Golang中map操作方法的相關資料,map是一種無序的基于key-value的數(shù)據(jù)結構,Go語言中map是引用類型,必須初始化才能使用,需要的朋友可以參考下
    2023-11-11
  • 一文總結Go語言切片核心知識點和坑

    一文總結Go語言切片核心知識點和坑

    都說Go的切片用起來絲滑得很,Java中的List怎么用,切片就怎么用,作為曾經的Java選手,因為切片的使用不得當,喜提缺陷若干,本文就給大家總結一下Go語言切片核心知識點和坑,需要的朋友可以參考下
    2023-06-06
  • Go語言中接口組合的實現(xiàn)方法

    Go語言中接口組合的實現(xiàn)方法

    這篇文章主要介紹了Go語言中接口組合的實現(xiàn)方法,實例分析了接口中包含接口的實現(xiàn)技巧,需要的朋友可以參考下
    2015-02-02
  • 關于Golang中for-loop與goroutine的問題詳解

    關于Golang中for-loop與goroutine的問題詳解

    這篇文章主要給大家介紹了關于Golang中for-loop與goroutine問題的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用golang具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
    2017-09-09
  • 詳解Go語言Sync.Pool為何不加鎖也能夠實現(xiàn)線程安全

    詳解Go語言Sync.Pool為何不加鎖也能夠實現(xiàn)線程安全

    在這篇文章中,我們將剖析sync.Pool內部實現(xiàn)中,介紹了sync.Pool比較巧妙的內部設計思路以及其實現(xiàn)方式。在這個過程中,也間接介紹了為何不加鎖也能夠實現(xiàn)線程安全,感興趣的可以學習一下
    2023-04-04
  • Go語言實現(xiàn)廣播式并發(fā)聊天服務器

    Go語言實現(xiàn)廣播式并發(fā)聊天服務器

    本文主要介紹了Go語言實現(xiàn)廣播式并發(fā)聊天服務器,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-08-08

最新評論