Reputation: 320
I currently have a problem in my project where i must find numbers that are not present in a slice. I found working code in the golang website, this works great. In my project i make a empty block and let the else statement do all the work. I tried to alter the code to remove the empty block but i got errors every time, i finaly found a example that reproduces the problem :
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
nr := 9
sort.Ints(data)
index := sort.Search(len(data), func(index int) bool { return data[index] == nr })
if index == len(data) {
fmt.Print("It's not in : ")
fmt.Println(nr)
} else {
fmt.Print("It's in! Index is at : ")
fmt.Println(index)
}
}
Working code on golang playground!
Upvotes: 4
Views: 5202
Reputation: 61
I encounter the same problem too, because I misunderstood the document in godoc sort Search
.
If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.
I thought that means "The documentation says that == is allowed" too. In fact, in the function as a parameter in sort.Search, can only use >=
or <=
, no ==
. And that sentence means after you got the index i
, you have to test it with data[i] == 23
to make sure 23 is in the slice.
Upvotes: 5
Reputation: 166598
For example,
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
sort.Ints(data)
fmt.Println(data)
x := 9
notpresent := false
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i >= len(data) || data[i] != x {
// x is not present in data,
// but i is the index where it would be inserted.
notpresent = true
}
fmt.Println(x, notpresent)
}
Output:
[4 8 9 12 15 17 19 21 23 25 27]
9 false
Upvotes: 4