-4

Example:

a_array := {"1","2","3","4,"}
b_array := {"3","4"}

Desired result:

"1","2"

With the assumption, a_array elements definitely has b_array elements.

tshepang
  • 12,111
  • 21
  • 91
  • 136
marumo
  • 21
  • 1
  • 1

1 Answers1

1

If you need to strictly compare one slice against the other you may do something along the lines of

func diff(a []string, b []string) []string {
    // Turn b into a map
    var m map[string]bool
    m = make(map[string]bool, len(b))
    for _, s := range b {
        m[s] = false
    }
    // Append values from the longest slice that don't exist in the map
    var diff []string
    for _, s := range a {
        if _, ok := m[s]; !ok {
            diff = append(diff, s)
            continue
        }
        m[s] = true
    }
    // Sort the resulting slice
    sort.Strings(diff)
    return diff
}

Go Playground


Alternatively if you want to get all values from both slices that are not present in both of them you can do

func diff(a []string, b []string) []string {
    var shortest, longest *[]string
    if len(a) < len(b) {
        shortest = &a
        longest = &b
    } else {
        shortest = &b
        longest = &a
    }
    // Turn the shortest slice into a map
    var m map[string]bool
    m = make(map[string]bool, len(*shortest))
    for _, s := range *shortest {
        m[s] = false
    }
    // Append values from the longest slice that don't exist in the map
    var diff []string
    for _, s := range *longest {
        if _, ok := m[s]; !ok {
            diff = append(diff, s)
            continue
        }
        m[s] = true
    }
    // Append values from map that were not in the longest slice
    for s, ok := range m {
        if ok {
            continue
        }
        diff = append(diff, s)
    }
    // Sort the resulting slice
    sort.Strings(diff)
    return diff
}

Then

fmt.Println(diff(a_array, b_array))

will give you

[1 2]

Go playground

peterm
  • 91,357
  • 15
  • 148
  • 157
  • Dif can't be done based longest or smallest sized set. That means, lets say `A[] = {1, 2}` and `B[] = {1, 2, 3, 4}` and if he wants `A dif B` ( `A\B` or ` A - B` in terms of set), then your program just give output `{3, 4}` where the correct answer is `{}`. Hope make sense. – Shudipta Sharma Nov 08 '18 at 13:08
  • First of all the suggested implementation is not based on shortest or smallest, it's just an implementation detail for a slightly different problem - get values from both slices that are not present in both of them or in other words eliminate all that present in both and give me the rest unique values, again, from both slices. From OP's question it's not clear what exactly is required - the result of subtracting two slices pretending they are sets or my interpretation. But I'll add another version that strictly compares `a` against `b`. – peterm Nov 08 '18 at 19:11