Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement numbers permutation #103

Merged
merged 2 commits into from
Nov 28, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
implement next permutation
  • Loading branch information
CengSin committed Nov 10, 2020
commit 1050b4208c48ef399fd84b03dcdc07337627eb0d
29 changes: 29 additions & 0 deletions permutation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package funk

import "errors"

// NextPermutation Implement next permutation,
// which rearranges numbers into the lexicographically next greater permutation of numbers.
func NextPermutation(nums []int) error {
n := len(nums)
if n == 0 {
return errors.New("nums is empty")
}

i := n - 2

for i >= 0 && nums[i] >= nums[i+1] {
i--
}

if i >= 0 {
j := n - 1
for j >= 0 && nums[i] >= nums[j] {
j--
}
nums[i], nums[j] = nums[j], nums[i]
}

ReverseInt(nums[i+1:])
return nil
}
34 changes: 34 additions & 0 deletions permutation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package funk

import (
"fmt"
"testing"
)

func TestNextPermutation(t *testing.T) {
type args struct {
nums []int
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "case1",
args: args{
nums: []int{1, 2, 3},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := NextPermutation(tt.args.nums); (err != nil) != tt.wantErr {
t.Errorf("NextPermutation() error = %v, wantErr %v", err, tt.wantErr)
} else {
fmt.Println(tt.args.nums)
}
})
}
}