Skip to content

Instantly share code, notes, and snippets.

@primayudantra
Last active October 9, 2018 08:59
Show Gist options
  • Select an option

  • Save primayudantra/2bd197818b53e9df8ceb21c52dca7c70 to your computer and use it in GitHub Desktop.

Select an option

Save primayudantra/2bd197818b53e9df8ceb21c52dca7c70 to your computer and use it in GitHub Desktop.
Intersection and Differences with Golang

How to get Intersection and Differences of 2 arrays with golang?

  1. Intersection
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 company_skill = []int{1, 2, 3, 4, 5, 6, 7 , 8 ,9 ,10}

      var user_skill = []int{1, 2, 3, 4, 5, 6, 7, 11}

      fmt.Println(Difference(company_skill, user_skill))
}

  1. Differences
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 company_skill = []int{1, 2, 3, 4, 5, 6, 7 , 8 ,9 ,10}

      var user_skill = []int{1, 2, 3, 4, 5, 6, 7, 11}

      fmt.Println(Difference(company_skill, user_skill))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment