From 87758d77a8bba9bcf7f845be67f21cc76929f23c Mon Sep 17 00:00:00 2001 From: xing Date: Tue, 25 Oct 2022 20:05:44 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8D=95=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- helper/func.go | 27 +++++++++++++++++++++++++++ helper/func_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/helper/func.go b/helper/func.go index 8cf13b3..114c328 100644 --- a/helper/func.go +++ b/helper/func.go @@ -8,6 +8,7 @@ import ( "math/rand" "reflect" "regexp" + "sort" "strings" ) @@ -261,3 +262,29 @@ func RandNum[T IntNumber](start, end T) T { end++ return T(rand.Int63n(int64(end-start))) + start } + +type anyArr[T any] struct { + data []T + fn func(i, j T) bool +} + +func (r anyArr[T]) Len() int { + return len(r.data) +} + +func (r anyArr[T]) Swap(i, j int) { + r.data[i], r.data[j] = r.data[j], r.data[i] +} + +func (r anyArr[T]) Less(i, j int) bool { + return r.fn(r.data[i], r.data[j]) +} + +func SampleSort[T any](arr []T, fn func(i, j T) bool) { + slice := anyArr[T]{ + data: arr, + fn: fn, + } + sort.Sort(slice) + return +} diff --git a/helper/func_test.go b/helper/func_test.go index 2267caa..f11425f 100644 --- a/helper/func_test.go +++ b/helper/func_test.go @@ -607,3 +607,33 @@ func TestRandNum(t *testing.T) { }) } } + +func TestSampleSort(t *testing.T) { + type args struct { + arr []int + fn func(i, j int) bool + } + tests := []struct { + name string + args args + wantR []int + }{ + { + name: "t1", + args: args{ + arr: []int{3, 5, 6, 1}, + fn: func(i, j int) bool { + return i < j + }, + }, + wantR: []int{1, 3, 5, 6}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if SampleSort(tt.args.arr, tt.args.fn); !reflect.DeepEqual(tt.args.arr, tt.wantR) { + t.Errorf("SampleSort() = %v, want %v", tt.args.arr, tt.wantR) + } + }) + } +}