ch6: fix code format

This commit is contained in:
chai2010
2016-01-21 10:08:07 +08:00
parent 20a8cf71b9
commit 2420954025
7 changed files with 90 additions and 88 deletions

View File

@@ -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()
}
```