Skip to content

Commit 5035611

Browse files
authored
Merge pull request thoas#103 from CengSin/feature_numbers_permutation
implement numbers permutation
2 parents 17a41bd + 1050b42 commit 5035611

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

permutation.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package funk
2+
3+
import "errors"
4+
5+
// NextPermutation Implement next permutation,
6+
// which rearranges numbers into the lexicographically next greater permutation of numbers.
7+
func NextPermutation(nums []int) error {
8+
n := len(nums)
9+
if n == 0 {
10+
return errors.New("nums is empty")
11+
}
12+
13+
i := n - 2
14+
15+
for i >= 0 && nums[i] >= nums[i+1] {
16+
i--
17+
}
18+
19+
if i >= 0 {
20+
j := n - 1
21+
for j >= 0 && nums[i] >= nums[j] {
22+
j--
23+
}
24+
nums[i], nums[j] = nums[j], nums[i]
25+
}
26+
27+
ReverseInt(nums[i+1:])
28+
return nil
29+
}

permutation_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package funk
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func TestNextPermutation(t *testing.T) {
9+
type args struct {
10+
nums []int
11+
}
12+
tests := []struct {
13+
name string
14+
args args
15+
wantErr bool
16+
}{
17+
{
18+
name: "case1",
19+
args: args{
20+
nums: []int{1, 2, 3},
21+
},
22+
wantErr: false,
23+
},
24+
}
25+
for _, tt := range tests {
26+
t.Run(tt.name, func(t *testing.T) {
27+
if err := NextPermutation(tt.args.nums); (err != nil) != tt.wantErr {
28+
t.Errorf("NextPermutation() error = %v, wantErr %v", err, tt.wantErr)
29+
} else {
30+
fmt.Println(tt.args.nums)
31+
}
32+
})
33+
}
34+
}

0 commit comments

Comments
 (0)