1 Star 0 Fork 0

CaptialSTeam/ubdframe

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
array.go 1.82 KB
一键复制 编辑 原始数据 按行查看 历史
Souki 提交于 2025-12-08 17:01 +08:00 . !7modify support
package utils
import (
"fmt"
)
// ArrayIntersection 取数组交集
func ArrayIntersection[T interface{}](slices ...[]T) []T {
elemCount := make(map[string]int)
elements := make(map[string]T)
for _, item := range slices {
temp := make(map[string]bool)
for _, v := range item {
k := fmt.Sprintf("%+v", v)
elements[k] = v
if _, exist := temp[k]; exist {
// 避免当前切片内重复元素干扰
continue
}
temp[k] = true
if _, exists := elemCount[k]; !exists {
elemCount[k] = 0
}
//计数
elemCount[k]++
}
}
var intersection []T
for k, v := range elemCount {
//计数值=总数组数则是所有数都存在的
if v == len(slices) {
intersection = append(intersection, elements[k])
}
}
return intersection
}
// ArrayDifference 取数组差集
func ArrayDifference[T interface{}](slices ...[]T) []T {
elemCount := make(map[string]int)
elements := make(map[string]T)
for _, item := range slices {
temp := make(map[string]bool)
for _, v := range item {
k := fmt.Sprintf("%+v", v)
fmt.Printf("%s\n", k)
elements[k] = v
if _, exist := temp[k]; exist {
// 避免当前切片内重复元素干扰
continue
}
temp[k] = true
if _, exists := elemCount[k]; !exists {
elemCount[k] = 0
}
//计数
elemCount[k]++
}
}
var intersection []T
for k, v := range elemCount {
//计数值=1表示只出现过一次的,即为差值
if v == 1 {
intersection = append(intersection, elements[k])
}
}
return intersection
}
// ArrayUnion 取数组并集
func ArrayUnion[T interface{}](slices ...[]T) []T {
var union []T
m := make(map[string]bool)
for _, item := range slices {
for _, v := range item {
k := fmt.Sprintf("%+v", v)
if _, exist := m[k]; exist {
continue
}
m[k] = true
union = append(union, v)
}
}
return union
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/captials-team/ubdframe.git
git@gitee.com:captials-team/ubdframe.git
captials-team
ubdframe
ubdframe
v1.0.4

搜索帮助