Search code examples
gocomparisonslice

Compare two slices


Is there a way in Go to compare two slices and get the elements in slice X that are not in slice Y and vice versa?

    X := []int{10, 12, 12, 12, 13}
    Y := []int{12, 14, 15}

func compare(X, Y []int)  

calling compare(X, Y)   
    result1 := []int{10, 12, 12, 13} // if you're looking for elements in slice X that are not in slice Y

calling compare(Y, X)
    result2 := []int{14, 15} // if you're looking for elements in slice Y that are not in slice X

Solution

  • Something like this should work:

    package main
    
    import "fmt"
    
    func main() {
        X := []int{10, 12, 12, 12, 13}
        Y := []int{12, 14, 15}
    
        fmt.Println(compare(X, Y))
        fmt.Println(compare(Y, X))
    }
    
    func compare(X, Y []int) []int {
        m := make(map[int]int)
    
        for _, y := range Y {
            m[y]++
        }
    
        var ret []int
        for _, x := range X {
            if m[x] > 0 {
                m[x]--
                continue
            }
            ret = append(ret, x)
        }
    
        return ret
    }
    

    http://play.golang.org/p/4DujR2staI