10

[Golang] Set Difference of Two Arrays

 2 years ago
source link: http://siongui.github.io/2018/03/14/go-set-difference-of-two-arrays/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Set Difference of Two Arrays

March 14, 2018

Find the elements in one array but not in the other, i.e., set difference of two arrays. In mathematical term:

A − B = {x ∈ A and x ∉ B}

The idea is to convert the array B to the data structure of key-value pairs, i.e., hash table. The hash table in Go is built-in map type. Then we check if items in array A is in the hash table. If not, append the item to the difference array, and return the difference array after finish.

The following is the implementation of above idea.

Run Code on Go Playground

package main

import (
      "fmt"
)

// Set Difference: A - B
func Difference(a, b []int) (diff []int) {
      m := make(map[int]bool)

      for _, item := range b {
              m[item] = true
      }

      for _, item := range a {
              if _, ok := m[item]; !ok {
                      diff = append(diff, item)
              }
      }
      return
}

func main() {
      var a = []int{1, 2, 3, 4, 5}
      var b = []int{2, 3, 5, 7, 11}
      fmt.Println(Difference(a, b))
}

The result will be [1 4].

Tested on: Go Playground


References:

[1][Golang] Intersection of Two Arrays

[2][Golang] Union of Two Arrays


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK