Browse Source

【杨】增加切片差集&交集&并集

master
yangzm 3 years ago
parent
commit
54c1b62e8b
2 changed files with 83 additions and 0 deletions
  1. +56
    -0
      slice.go
  2. +27
    -0
      slice_test.go

+ 56
- 0
slice.go View File

@ -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
}

+ 27
- 0
slice_test.go View File

@ -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)
}

Loading…
Cancel
Save