0

There is two slices in string type.I want to finding intercept result in set from the two slices in golang.I want to find the best solution rather than iterating each slice.

first_slice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E0","84-18-3A-2F-05-E8" } 
second_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8","F8-E7-1E-54-AE-08"}


Output:
    result_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8"}

I have use following approaches but it is not best approaches for large data set.

var result_slice *[]string

for _, i := range first_slice {
    for _, x := range second_slice {
        if i == x {
            &result_slice.append(i)
        }
    }
}

Appreciate if give me good solution that.

Sandun Priyanka
  • 591
  • 7
  • 24
  • These are `slice`, not array ! – Boris Le Méec Nov 23 '16 at 14:18
  • 2
    Stuff the strings of the shorter slice into a map as the keys for O(1) lookup of existence and iterate the longer slice looking up the values in the map appending to the result set if found. Requires more memory than your approach. Tradeoffs as usual. – Volker Nov 23 '16 at 14:19
  • 1
    Related / possible duplicates: [Check if a value is in a list](http://stackoverflow.com/a/30452518/1705598); and [How can I create an array that contains unique strings?](http://stackoverflow.com/a/33207265/1705598); and [Efficient way to check IP in slice of IP addresses in Golang](http://stackoverflow.com/a/39249045/1705598); and [Finding Unique Items in a Go Slice or Array](http://stackoverflow.com/a/34111576/1705598) – icza Nov 23 '16 at 14:30

1 Answers1

2
firstSlice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30",
    "84-18-3A-2F-05-E0", "84-18-3A-2F-05-E8"}
secondSlice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8",
    "F8-E7-1E-54-AE-08"}

resultSlice := []string{}
checkMap := map[string]struct{}{}

for _, addr := range firstSlice {
    checkMap[addr] = struct{}{}
}
for _, addr := range secondSlice {
    if _, ok := checkMap[addr]; ok {
        resultSlice = append(resultSlice, addr)
    }
}

fmt.Println(resultSlice)

The output is what you want.

An empty struct takes no space in monery

What's more, always use camel in golang.

PapEr
  • 815
  • 5
  • 16