-2

Question is as stated in the title. Given two lists of known types, and you just wanted to make sure that both lists aren't using any of the same elements, how do you check that efficiently in golang.

Still relatively new to golang. In Python, I would probably do something like this:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 1]

def check_lists_are_unique(list_one, list_two):
    return not bool(len(set(list_one) & set(list_two)))

print(check_lists_are_unique(a, b)) # returns True
print(check_lists_are_unique(a, c)) # returns False
print(check_lists_are_unique(b, c)) # returns True

My own naive first attempt in golang would be:

a := []int{1, 2, 3}
b := []int{4, 5, 6}
c := []int{7, 8, 1}

checkUnique := func(listOne, listTwo []int) bool {
    for _, i := range listOne {
        for _, j := range listTwo {
            if i == j {
                return false
            }
        }
    }
    return true
}
fmt.Println(checkUnique(a, b)) // returns true
fmt.Println(checkUnique(a, c)) // returns false
fmt.Println(checkUnique(b, c)) // returns true

https://play.golang.org/p/vuBnv97MyWb

Was wondering if this is really the most efficient way to do this comparison in golang? Are there alternatives or a more "correct" way of doing this comparison in golang?

Extra note: Would also like to hear any cool/creative/wacky ways of doing this that are uniquely golang-ish.

m_cheah
  • 131
  • 1
  • 1
  • 8
  • 3
    This is the most efficient method for small sets in most cases and languages (lines of code != efficiency). "Creative" or "wacky" are not something promoted by Go. If you want to check membership in larger sets with basic types, use a map. – JimB Mar 07 '20 at 14:02
  • I suggest to using map then you can append the map – Kyoo Mar 07 '20 at 14:50

1 Answers1

1

I agree with @JimB. Your example is an efficient way to compare slices. See map vs switch performance in go. Comparing slices of bytes instead of strings is also efficient. See Better to compare slices or bytes?. This might also be true for integers. See the code below and https://play.golang.org/p/w59ctLV9C9S.

  a := []byte{1, 2, 3}
  b := []byte{4, 5, 6}
  c := []byte{7, 8, 1}

  checkUnique := func(listOne, listTwo []byte) bool {
     for _, i := range listOne {
        for _, j := range listTwo {
           if i == j {
              return false
           }
        }
     }
     return true
  }
  fmt.Println(checkUnique(a, b)) // returns true
  fmt.Println(checkUnique(a, c)) // returns false
  fmt.Println(checkUnique(b, c)) // returns true

It may not be applicable to your question, but bytes.Equal is efficient for comparing two []byte. See Checking the equality of two slices.