自定义交集 并集 差集
package main
import "fmt"
func main() {
aList := []string{
"1", "2", "3", "4", "5"}
bList := []string{
"4", "5", "6", "7", "8"}
ss := new(baseStruct)
unionList := ss.union(aList, bList)
intersectList := ss.intersect(aList, bList)
diffList1, diffList2 := ss.difference(aList, bList)
fmt.Printf("交集:%v\n", intersectList)
fmt.Printf("并集:%v\n", unionList)
fmt.Printf("差集(属a不属b):%v\n", diffList1)
fmt.Printf("差集(属b不属a):%v\n", diffList2)
//交集:[4 5]
//并集:[1 2 3 4 5 6 7 8]
//差集(属a不属b):[1 2 3]
//差集(属b不属a):[6 7 8]
}
type baseStruct struct{
}
//并集
func (s *baseStruct) union(outApiList, LocalDBList []string) []string {
baseMap := make(map[string]int)
unionList := make([]string, 0)
for _, name := range outApiList {
baseMap[name] ++
unionList = append(unionList, name)
}
for _, name := range LocalDBList {
//如果不在基础数据中 则加入并集列表
if baseMap[name] == 0 {
unionList = append(unionList, name)
}
}
return unionList
}
//交集
func (s *baseStruct) intersect(outApiList, LocalDBList []string) []string {
baseMap := make(map[string]int)
for _, name := range outApiList {
baseMap[name] ++
}
intersectList := make([]string, 0)
for _, name := range LocalDBList {
//如果在基础数据中 则加入交集列表
if baseMap[name] == 1 {
intersectList = append(intersectList, name)
}
}
return intersectList
}
//求差集
func (s *baseStruct) difference(outApiList, LocalDBList []string) (addList, delList []string) {
//查出交集 取各个差集
baseMap := make(map[string]int)
intersectList := s.intersect(outApiList, LocalDBList)
for _, v := range intersectList {
baseMap[v]++
}
//api不在交集列表中
apiNotIntersect := make([]string, 0)
for _, name := range outApiList {
if baseMap[name] == 0 {
apiNotIntersect = append(apiNotIntersect, name)
}
}
//local不在交集列表中
localNotIntersect := make([]string, 0)
for _, name := range LocalDBList {
if baseMap[name] == 0 {
localNotIntersect = append(localNotIntersect, name)
}
}
return apiNotIntersect, localNotIntersect
}
set包处理交集 并集 差集
package main
import (
"fmt"
"github.com/fatih/set"
)
func main() {
aList := []int{
1, 2, 3, 4, 5}
a := set.New(set.ThreadSafe)
for _, v := range aList {
a.Add(v)
}
bList := []int{
4, 5, 6, 7, 8}
b := set.New(set.ThreadSafe)
for _, v := range bList {
b.Add(v)
}
//并集
unionSet := set.Union(a, b)
fmt.Printf("并集:%v\n", unionSet)
//并集:[4, 5, 7, 8, 6, 1, 2, 3]
//交集
intersectionSet := set.Intersection(a, b)
fmt.Printf("交集:%v\n", intersectionSet)
//交集:[4, 5]
//差集
diffS1S2 := set.Difference(a, b)
fmt.Printf("差集(属a不属b):%v\n", diffS1S2)
//差集(属a不属b):[1, 2, 3]
diffS2S1 := set.Difference(b, a)
fmt.Printf("差集(属b不属a):%v\n", diffS2S1)
//差集(属b不属a):[6, 7, 8]
//返回的是接口 需要断言
for _,v := range unionSet.List(){
fmt.Println(v.(int))
}
}
转载:https://blog.csdn.net/Moniicoo/article/details/115769184
查看评论