fix: combination.WithValidatorHandleNCarryM 修复 M 允许类型不同的问题

This commit is contained in:
kercylan98
2023-08-02 18:04:31 +08:00
parent faac7b27bb
commit 0db1e5c30b
2 changed files with 76 additions and 34 deletions
+34 -34
View File
@@ -197,6 +197,40 @@ func WithValidatorHandleGroupContinuousN[T Item, E generic.Ordered, Index generi
// - m: 组合中元素的数量,表示需要匹配的组合数量,m 的类型需要全部相同
// - getType: 用于获取组合中元素的类型,用于判断是否相同
func WithValidatorHandleNCarryM[T Item, E generic.Ordered](n, m int, getType func(item T) E) ValidatorOption[T] {
return WithValidatorHandle[T](func(items []T) bool {
if len(items) != n+m {
return false // 总数量不符合 n + m
}
typeCount := make(map[E]int)
for _, item := range items {
t := getType(item)
typeCount[t]++
}
if len(typeCount) != 2 {
return false
}
foundN := false
foundM := false
for _, count := range typeCount {
if count == n {
foundN = true
} else if count == m {
foundM = true
}
}
return foundN && foundM
})
}
// WithValidatorHandleNCarryIndependentM 校验组合成员是否匹配 N 携带独立的 M 的组合
// - n: 组合中元素的数量,表示需要匹配的组合数量,n 的类型需要全部相同
// - m: 组合中元素的数量,表示需要匹配的组合数量,m 的类型无需全部相同
// - getType: 用于获取组合中元素的类型,用于判断是否相同
func WithValidatorHandleNCarryIndependentM[T Item, E generic.Ordered](n, m int, getType func(item T) E) ValidatorOption[T] {
return WithValidatorHandle[T](func(items []T) bool {
if len(items) != n+m {
return false // 总数量不符合 n + m
@@ -230,37 +264,3 @@ func WithValidatorHandleNCarryM[T Item, E generic.Ordered](n, m int, getType fun
return true // 符合 N 带 M 的条件
})
}
// WithValidatorHandleNCarryIndependentM 校验组合成员是否匹配 N 携带独立的 M 的组合
// - n: 组合中元素的数量,表示需要匹配的组合数量,n 的类型需要全部相同
// - m: 组合中元素的数量,表示需要匹配的组合数量,m 的类型无需全部相同
// - getType: 用于获取组合中元素的类型,用于判断是否相同
func WithValidatorHandleNCarryIndependentM[T Item, E generic.Ordered](n, m int, getType func(item T) E) ValidatorOption[T] {
return WithValidatorHandle[T](func(items []T) bool {
if len(items) != n+m {
return false // 总数量不符合 n + m
}
typeCount := make(map[E]int)
for _, item := range items {
t := getType(item)
typeCount[t]++
}
if len(typeCount) != 2 {
return false
}
foundN := false
foundM := false
for _, count := range typeCount {
if count == n {
foundN = true
} else if count == m {
foundM = true
}
}
return foundN && foundM
})
}