mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-08-09 16:42:26 +00:00
ch6: fix code format
This commit is contained in:
@@ -4,38 +4,38 @@ Go語言里的集合一般會用map[T]bool這種形式來表示,T代表元素
|
||||
|
||||
一個bit數組通常會用一個無符號數或者稱之爲“字”的slice或者來表示,每一個元素的每一位都表示集合里的一個值。當集合的第i位被設置時,我們才説這個集合包含元素i。下面的這個程序展示了一個簡單的bit數組類型,併且實現了三個函數來對這個bit數組來進行操作:
|
||||
|
||||
<u><i>gopl.io/ch6/intset</i></u>
|
||||
```go
|
||||
gopl.io/ch6/intset
|
||||
// An IntSet is a set of small non-negative integers.
|
||||
// Its zero value represents the empty set.
|
||||
type IntSet struct {
|
||||
words []uint64
|
||||
words []uint64
|
||||
}
|
||||
|
||||
// Has reports whether the set contains the non-negative value x.
|
||||
func (s *IntSet) Has(x int) bool {
|
||||
word, bit := x/64, uint(x%64)
|
||||
return word < len(s.words) && s.words[word]&(1<<bit) != 0
|
||||
word, bit := x/64, uint(x%64)
|
||||
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/64, uint(x%64)
|
||||
for word >= len(s.words) {
|
||||
s.words = append(s.words, 0)
|
||||
}
|
||||
s.words[word] |= 1 << bit
|
||||
word, bit := x/64, uint(x%64)
|
||||
for word >= len(s.words) {
|
||||
s.words = append(s.words, 0)
|
||||
}
|
||||
s.words[word] |= 1 << bit
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
for i, tword := range t.words {
|
||||
if i < len(s.words) {
|
||||
s.words[i] |= tword
|
||||
} else {
|
||||
s.words = append(s.words, tword)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
@@ -46,23 +46,23 @@ func (s *IntSet) UnionWith(t *IntSet) {
|
||||
```go
|
||||
// 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 < 64; j++ {
|
||||
if word&(1<<uint(j)) != 0 {
|
||||
if buf.Len() > len("{") {
|
||||
buf.WriteByte('}')
|
||||
}
|
||||
fmt.Fprintf(&buf, "%d", 64*i+j)"}")}}
|
||||
}
|
||||
}
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
return buf.String()
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte('{')
|
||||
for i, word := range s.words {
|
||||
if word == 0 {
|
||||
continue
|
||||
}
|
||||
for j := 0; j < 64; j++ {
|
||||
if word&(1<<uint(j)) != 0 {
|
||||
if buf.Len() > len("{") {
|
||||
buf.WriteByte('}')
|
||||
}
|
||||
fmt.Fprintf(&buf, "%d", 64*i+j)"}")}}
|
||||
}
|
||||
}
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
return buf.String()
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user