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) + } + }) + } +}