diff --git a/utils/maths/compare.go b/utils/maths/compare.go index b7d7c85..12dd246 100644 --- a/utils/maths/compare.go +++ b/utils/maths/compare.go @@ -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) +} diff --git a/utils/maths/compare_example_test.go b/utils/maths/compare_example_test.go new file mode 100644 index 0000000..e62a7ba --- /dev/null +++ b/utils/maths/compare_example_test.go @@ -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 +}