From 54c1b62e8bedaffb990d22c4f146c2c29074760c Mon Sep 17 00:00:00 2001 From: yangzm <18675616014@163.com> Date: Mon, 6 Dec 2021 19:32:33 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90=E6=9D=A8=E3=80=91=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=88=87=E7=89=87=E5=B7=AE=E9=9B=86&=E4=BA=A4=E9=9B=86&?= =?UTF-8?q?=E5=B9=B6=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- slice.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++ slice_test.go | 27 +++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 slice.go create mode 100644 slice_test.go diff --git a/slice.go b/slice.go new file mode 100644 index 0000000..6627ebb --- /dev/null +++ b/slice.go @@ -0,0 +1,56 @@ +/* + * string functions + */ +package helper + +// 求差集 +func Diff(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + inter := Intersect(slice1, slice2) + for _, v := range inter { + m[v]++ + } + + for _, value := range slice1 { + times, _ := m[value] + if times == 0 { + nn = append(nn, value) + } + } + return nn +} + +// 求交集 +func Intersect(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 1 { + nn = append(nn, v) + } + } + return nn +} + +// 求并集 +func Union(slice1, slice2 []string) []string { + m := make(map[string]int) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 0 { + slice1 = append(slice1, v) + } + } + return slice1 + +} diff --git a/slice_test.go b/slice_test.go new file mode 100644 index 0000000..9217c1b --- /dev/null +++ b/slice_test.go @@ -0,0 +1,27 @@ +package helper + +import ( + "fmt" + "testing" +) + +func Test_Diff(t *testing.T) { + var aa = []string{"43", "33"} + var bb = []string{"2", "33", "1"} + cc := Diff(aa, bb) + fmt.Println(cc) +} + +func Test_Intersect(t *testing.T) { + var aa = []string{"43", "33"} + var bb = []string{"2", "33", "1"} + cc := Intersect(aa, bb) + fmt.Println(cc) +} + +func Test_Union(t *testing.T) { + var aa = []string{"43", "33"} + var bb = []string{"2", "33", "1"} + cc := Union(aa, bb) + fmt.Println(cc) +}