go - Reduce array length -



go - Reduce array length -

am trying merge 2 string array one. resulting array should have duplicates element removed.

func mergearrays(str1, str2 []string) []string { c := make([]string, len(str1)+len(str2), cap(str1)+cap(str2)) k := make(map[string]bool) i, s := range str1 { if _, ok := k[s]; !ok { c[i] = s k[s] = true } } j, s := range str2 { if _, ok := k[s]; !ok { c[j+len(str1)] = s k[s] = true } } homecoming c }

test data

str1 := []string{"a", "b"} str2 := []string{"c", "d", "a"}

output: "a", "b", "c", "d" length of array "5"

am getting output want, length of array should 4 , not 5. can understand why prints 5, want output array of length 4. there other way merge 2 arrays.

start length of 0 , add together 1 when append element. example,

package main import "fmt" func mergearrays(a1, a2 []string) []string { m := make([]string, 0, len(a1)+len(a2)) k := make(map[string]bool, len(a1)+len(a2)) _, aa := range [][]string{a1, a2} { _, s := range aa { if !k[s] { m = append(m, s) k[s] = true } } } homecoming m } func main() { a1 := []string{"a", "b"} a2 := []string{"c", "d", "a"} m := mergearrays(a1, a2) fmt.println(len(m), m) }

output:

4 [a b c d]

go slice

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -