gopl icon indicating copy to clipboard operation
gopl copied to clipboard

Issue in IntersectWith implementation in Exercise 6.3 (P167)

Open technusm1 opened this issue 1 year ago • 0 comments

Thanks for the great repo. I found an issue in IntersectWith method, here's the driver code that reproduces issue:

func main() {
	var x, y IntSet
	x.AddAll(1, 2)
	y.AddAll(128, 129)
	x.IntersectWith(&y)
	fmt.Println(x.String())
}

Got: {128 129} Expected: {}

Here's an implementation that works:

// IntersectWith sets s to the intersection of s and t.
func (s *IntSet) IntersectWith(t *IntSet) {
	var min int
	if len(s.words) > len(t.words) {
		min = len(t.words)
	} else {
		min = len(s.words)
	}
	for i := 0; i < min; i++ {
		s.words[i] &= t.words[i]
	}
	for i := min; i < len(s.words); i++ {
		s.words[i] = 0
	}
}

technusm1 avatar Sep 01 '22 09:09 technusm1