The following column Golang Tutorial will introduce to you the implementation method of Bit array in Golang. I hope it will be helpful to friends in need!
Go languageCommon methods for implementing Bit arrays
Collections in Go language generally use map[T]bool In this form, T represents the element type. Collections are represented using map types, which is very flexible, but we can represent it in a better form. For example, in the field of data flow analysis, the set element is usually a non-negative integer, the set will contain many elements, and the set will often perform union and intersection operations. In this case, the bit array will perform more ideally than the map.
A bit array is usually represented by an unsigned number or a slice called a "word". Each bit of each element represents a value in the set. When the i-th bit of a set is set, we say that the set contains element i. The following program shows a simple bit array type and implements three functions to operate on this bit array:
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)) //根据平台自动判断决定是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) } } }
Because each word has 64 binary bits, in order to locate x bit, we use the quotient of x/64 as the subscript of the word, and use the value obtained by xd as the position of the bit in the word.
For example, for the number 1, add it to the bit array:
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数组变为了[]uint64{2}
Similarly, if we add 66 to the bit array:
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 } // 继续把66存入后,words数组变为了[]uint64{2, 4}
So, for words, each There are 64 values that can be stored in each element. Every time the value exceeds 64, a carry is performed, that is, an element is added. (Note that 0 also occupies one bit, so 64 needs to be carried, and the first element can store 0-63).
So, for an element in words, when you want to convert it to a specific value: first get its position i, use 64 * i as the number of carries (similar to carrying every 10 digits), and then This element is converted into a binary number. Counting from right to left, the number of digits is 1, which means that the corresponding value is present. The number of digits x 64 *i is the value we store.
Correspondingly, there can be the following String() function
// 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() }
For example, after storing 1 and 66 previously, the conversion process is:
// []uint64{2 4} // 对于2: 1 << 1 = 2; 所以 x = 0 * 64 + 1 // 对于4: 1 << 2 = 4; 所以 x = 1 * 64 + 2 // 所以转换为String为{1 66}
Implement other bit arrays Method function
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中均出现 func (s *IntSet) IntersectWith(t *IntSet) { for i, tword := range t.words { if i >= len(s.words) { continue } s.words[i] &= tword } } //A与B的差集,元素出现在A未出现在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的并差集,元素出现在A没有出现在B,或出现在B没有出现在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) } } } //获取比特数组中的所有元素的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 }
At this point, the common method functions of bit arrays have been implemented, and you can now use it.
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 } }
The above is the detailed content of How to implement Bit array in Golang (code example). For more information, please follow other related articles on the PHP Chinese website!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
