feat: maths 包支持比较一组数是否连续

可以通过 maths.Continuity 和 math.IsContinuityWithSort 比较一组数是否连续
This commit is contained in:
kercylan98 2023-06-30 09:15:28 +08:00
parent 390e8e75ef
commit 0ab38c7023
2 changed files with 45 additions and 1 deletions

View File

@ -1,6 +1,10 @@
package maths
import "github.com/kercylan98/minotaur/utils/generic"
import (
"github.com/kercylan98/minotaur/utils/generic"
"github.com/kercylan98/minotaur/utils/slice"
"sort"
)
const (
CompareGreaterThan CompareExpression = 1 // 大于
@ -29,3 +33,29 @@ func Compare[V generic.Ordered](a V, expression CompareExpression, b V) bool {
}
panic("unknown expression")
}
// IsContinuity 检查一组值是否连续
func IsContinuity[V generic.Integer](values []V) bool {
length := len(values)
if length == 0 {
return false
}
if length == 1 {
return true
}
for i := 1; i < length; i++ {
if values[i] != values[i-1]+1 {
return false
}
}
return true
}
// IsContinuityWithSort 检查一组值排序后是否连续
func IsContinuityWithSort[V generic.Integer](values []V) bool {
sli := slice.Copy(values)
sort.Slice(sli, func(i, j int) bool {
return sli[i] < sli[j]
})
return IsContinuity(sli)
}

View File

@ -0,0 +1,14 @@
package maths_test
import (
"fmt"
"github.com/kercylan98/minotaur/utils/maths"
)
func ExampleIsContinuity() {
fmt.Println(maths.IsContinuity([]int{1, 2, 3, 4, 5, 6, 7}))
fmt.Println(maths.IsContinuity([]int{1, 2, 3, 5, 5, 6, 7}))
// Output:
// true
// false
}