From 0ab38c7023d37da81967d03392d8dfdb8d715c89 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 30 Jun 2023 09:15:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20maths=20=E5=8C=85=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=AF=94=E8=BE=83=E4=B8=80=E7=BB=84=E6=95=B0=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E8=BF=9E=E7=BB=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可以通过 maths.Continuity 和 math.IsContinuityWithSort 比较一组数是否连续 --- utils/maths/compare.go | 32 ++++++++++++++++++++++++++++- utils/maths/compare_example_test.go | 14 +++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 utils/maths/compare_example_test.go 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 +}