收纳数组相关的操作工具
1. 两个数组并集
//求并集
func Union(slice1, slice2 []string) (newSlice []string) {
tmp := make(map[string]int)
newSlice = make([]string, 0)
for _, v := range slice1 {
tmp[v]++
newSlice = append(newSlice, v)
}
for _, v := range slice2 {
times, _ := tmp[v]
if times == 0 {
newSlice = append(newSlice, v)
}
}
return
}
2. 两个数组交集
//求交集
func Intersect(slice1, slice2 []string) (newSlice []string) {
tmp := make(map[string]int)
newSlice = make([]string, 0)
for _, v := range slice1 {
tmp[v]++
}
for _, v := range slice2 {
times, _ := tmp[v]
if times == 1 {
newSlice = append(newSlice, v)
}
}
return
}
3. 两个数组差集
//包含在slice1但是不包含在slice2中元素集合
func Except(slice1, slice2 []string) (newArr []string) {
newArr = make([]string, 0)
for _, data := range slice1 {
contains, _ := Contains(data, slice2)
if !contains {
newArr = append(newArr, data)
}
}
return
}
4. 数组是否包含元素
//target是否包含obj
func Contains(obj interface{}, target interface{}) (bool, error) {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true, nil
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true, nil
}
}
return false, errors.New("target don't contains data")
}
5. 去除数组中的重复元素
//去除重复元素
func RemoveDuplicate(arr []string) []string {
resArr := make([]string, 0)
tmpMap := make(map[string]interface{})
for _, val := range arr {
if _, ok := tmpMap[val]; !ok {
resArr = append(resArr, val)
tmpMap[val] = struct{}{}
}
}
return resArr
}
Test:
package slice
import (
"log"
"strings"
"testing"
)
var slice1 = []string{"1","2","3","4"}
var slice2 = []string{"3","4","5"}
var slice3 = []string{"1","2","2","3","3"}
func TestUnion(t *testing.T) {
newSlice := Union(slice1, slice2)
log.Printf("union data: %s", strings.Join(newSlice,","))
}
func TestIntersect(t *testing.T) {
newSlice := Intersect(slice1, slice2)
log.Printf("intersect data: %s ", strings.Join(newSlice, ","))
}
func TestRemoveRepeatedElement(t *testing.T) {
newArr := RemoveDuplicate(slice3)
log.Printf("remove repeated element: %s", strings.Join(newArr,","))
}
func TestExcept(t *testing.T) {
newArr := Except(slice1, slice2)
log.Printf("except: %s", strings.Join(newArr,","))
}
func TestContains(t *testing.T) {
contains, e := Contains("a", slice1)
if e != nil {
log.Printf(e.Error())
}
log.Printf("slice1 contains a : %t", contains)
b, e := Contains("1", slice1)
if e != nil {
log.Fatalf(e.Error())
}
log.Printf("slice1 contains 1 : %t", b)
}
Test Result:
image.png
网友评论