I have this but it is not working properly :
var i int
var names = []string{"F5", "F7", "C6", "H5", "G5"}
var board = []string{"B4", "D4", "G5", "F5", "F7", "C6"}
for i = 0; i < len(names)-1; i++ {
for k := 0; k < len(board)-1; k++ {
if names[i] != board[k] {
names = append(names[:i], names[i+1:]...)
}
}
}
fmt.Printf("%s ", names[i])
You need the intersection of two slices (delete the unique values from the first slice), try this working sample code (and notice the i++
):
package main
import "fmt"
func main() {
names := []string{"F5", "F7", "C6", "H5", "G5"}
board := []string{"B4", "D4", "G5", "F5", "F7", "C6"}
for i := 0; i < len(names); {
exist := false
for _, b := range board {
if b == names[i] {
exist = true
break
}
}
if !exist {
names = append(names[:i], names[i+1:]...) // delete names[i]
} else {
i++
}
}
fmt.Println(names) // [F5 F7 C6 G5]
}
output:
[F5 F7 C6 G5]
Also you may use this for the intersection of two slices with new result
, try this working sample code:
package main
import "fmt"
func main() {
names := []string{"F5", "F7", "C6", "H5", "G5"}
board := []string{"B4", "D4", "G5", "F5", "F7", "C6"}
result := make([]string, 0, 11)
for _, v := range names {
exist := false
for _, w := range board {
if v == w {
exist = true
break
}
}
if exist {
result = append(result, v)
}
}
fmt.Println(result) // [F5 F7 C6 G5]
}
output:
[F5 F7 C6 G5]
or if you need The union of two slices, try this working sample code:
package main
import "fmt"
func main() {
names := []string{"F5", "F7", "C6", "H5", "G5"}
board := []string{"B4", "D4", "G5", "F5", "F7", "C6"}
for _, b := range board {
exist := false
for _, n := range names {
if n == b {
exist = true
break
}
}
if !exist {
names = append(names, b)
}
}
fmt.Println(names) // [F5 F7 C6 H5 G5 B4 D4]
}
output:
[F5 F7 C6 H5 G5 B4 D4]
You are updating names
inside your inner for
loop. However, your inner loop is also logically incorrect. The very first value in board
not equal to a value in names
will empty names
. This also causes an index out of range
error.
You can try something like this:
var names = []string{"F5", "F7", "C6", "H5", "G5"}
var board = []string{"B4", "D4", "G5", "F5", "F7", "C6"}
results := make([]string, 0) // slice tostore the result
for i := 0; i < len(names); i++ {
for k := 0; k < len(board); k++ {
if names[i] != board[k] {
continue
}
// append a value in result only if
// it exists both in names and board
results = append(results, names[i])
}
}
fmt.Printf("%v %d
", results, len(results))
Example: https://play.golang.org/p/cQpzbvCGpO
You can create a map
out of one of your arrays and avoid the nested loop, for example:
package main
import (
"fmt"
)
func main() {
var names = []string{"F5", "F7", "C6", "H5", "G5"}
var board = []string{"B4", "D4", "G5", "F5", "F7", "C6"}
var board_map = make(map[string]bool)
for _, ele := range board {
board_map[ele] = true
}
var result []string
for _, name := range names {
if board_map[name] {
result = append(result, name)
}
}
fmt.Println(result)
}