0

I have two slice A := []string{"a","b","c","d"} and B := []string{"a","b"}.

How to get ["c","d"] from slice A?

I've tried various ways but still not getting the result I want. Thank you

package main

import (
    "fmt"
)


func main() {
    A := []string{"a","b","c","d"}
    B := []string{"a","b"}
    temp := []string{}
    
    for _, a := range A {
        for _, b := range B {
            if a == b {
                fmt.Printf("%s == %s\n", a,b)
                temp = append(temp, a)
                break
            }       
        }
        
    }
    
}


dwlpra
  • 76
  • 7

3 Answers3

1

You almost got it. Note if a was found in B. If a was not found in B, then add a to the result.

func main() {
    A := []string{"a", "b", "c", "d"}
    B := []string{"a", "b"}
    var result []string

    for _, a := range A {
        found := false
        for _, b := range B {
            if a == b {
                found = true
                break
            }
        }
        if !found {
            result = append(result, a)
        }
    }
    fmt.Println(result)
}
0
func main() {
    A := []string{"a", "b", "c", "d"}
    B := []string{"a", "b"}

    var outterLoop, innerLoop []string

    if len(A) > len(B) {
        outterLoop = A
        innerLoop = B
    } else {
        outterLoop = B
        innerLoop = A
    }
    temp := []string{}
    for _, b := range outterLoop {
        found := false
        for _, a := range innerLoop {
            if a == b {
                found = true
            }
        }
        if !found {
            temp = append(temp, b)
        }
    }

    for _, t := range temp {
        println(t)
    }
}
Erick Wang
  • 33
  • 1
  • 3
0
package main

import "fmt"

func find(a, b []string) []string {
    bm := make(map[string]struct{}, len(b))
    ok := false
    for i := range b {
        if _, ok = bm[b[i]]; !ok {
            bm[b[i]] = struct{}{}
        }
    }

    res := make([]string, 0)
    for i := range a {
        if _, ok = bm[a[i]]; !ok {
            res = append(res, a[i])
        }
    }

    return res
}

func main() {
    a := []string{"a", "b", "c", "d"}
    b := []string{"a", "b"}

    t := find(a, b)

    fmt.Println(t)
}
shmsr
  • 3,802
  • 2
  • 18
  • 29