This commit is contained in:
xing 2022-11-20 12:32:58 +08:00
parent 0bb5d85c8d
commit cb2de22b13
2 changed files with 148 additions and 0 deletions

View File

@ -334,3 +334,40 @@ func SliceChunk[T any](arr []T, size int) [][]T {
func NumberToString[T IntNumber | ~float64 | ~float32](n T) string {
return fmt.Sprintf("%v", n)
}
func Slice[T any](arr []T, offset, length int) (r []T) {
l := len(arr)
if length == 0 {
length = l - offset
}
if l > offset && l >= offset+length {
r = append(make([]T, 0, length), arr[offset:offset+length]...)
arr = append(arr[:offset], arr[offset+length:]...)
} else if l <= offset {
return
} else if l > offset && l < offset+length {
r = append(make([]T, 0, length), arr[offset:]...)
arr = arr[:offset]
}
return
}
func Comb[T any](arr []T, m int) (r [][]T) {
r = make([][]T, 0)
if m == 1 {
for _, t := range arr {
r = append(r, []T{t})
}
return
}
l := len(arr) - m
for i := 0; i <= l; i++ {
next := Slice(arr, i+1, 0)
nexRes := Comb(next, m-1)
for _, re := range nexRes {
t := append([]T{arr[i]}, re...)
r = append(r, t)
}
}
return r
}

View File

@ -797,3 +797,114 @@ func TestNumberToString(t *testing.T) {
})
}
}
func TestSlice(t *testing.T) {
type args struct {
arr []int
offset int
length int
}
tests := []struct {
name string
args args
wantR []int
}{
{
name: "t1",
args: args{
arr: RangeSlice(1, 10, 1),
offset: 3,
length: 2,
},
wantR: RangeSlice(4, 5, 1),
},
{
name: "t2",
args: args{
arr: RangeSlice(1, 10, 1),
offset: 3,
length: 0,
},
wantR: RangeSlice(4, 10, 1),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if gotR := Slice(tt.args.arr, tt.args.offset, tt.args.length); !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("Slice() = %v, want %v", gotR, tt.wantR)
}
})
}
}
func TestComb(t *testing.T) {
type args struct {
arr []int
m int
}
tests := []struct {
name string
args args
wantR [][]int
}{
{
name: "t1",
args: args{
arr: RangeSlice(1, 5, 1),
m: 2,
},
wantR: [][]int{
{1, 2},
{1, 3},
{1, 4},
{1, 5},
{2, 3},
{2, 4},
{2, 5},
{3, 4},
{3, 5},
{4, 5},
},
},
{
name: "t2",
args: args{
arr: RangeSlice(1, 5, 1),
m: 3,
},
wantR: [][]int{
{1, 2, 3},
{1, 2, 4},
{1, 2, 5},
{1, 3, 4},
{1, 3, 5},
{1, 4, 5},
{2, 3, 4},
{2, 3, 5},
{2, 4, 5},
{3, 4, 5},
},
},
{
name: "t3",
args: args{
arr: RangeSlice(1, 5, 1),
m: 4,
},
wantR: [][]int{
{1, 2, 3, 4},
{1, 2, 3, 5},
{1, 2, 4, 5},
{1, 3, 4, 5},
{2, 3, 4, 5},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if gotR := Comb(tt.args.arr, tt.args.m); !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("Comb() = %v, want %v", gotR, tt.wantR)
}
})
}
}