From 1050b4208c48ef399fd84b03dcdc07337627eb0d Mon Sep 17 00:00:00 2001 From: zhangzetao Date: Tue, 10 Nov 2020 17:12:20 +0800 Subject: [PATCH] implement next permutation --- permutation.go | 29 +++++++++++++++++++++++++++++ permutation_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 permutation.go create mode 100644 permutation_test.go diff --git a/permutation.go b/permutation.go new file mode 100644 index 0000000..0b10993 --- /dev/null +++ b/permutation.go @@ -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 +} diff --git a/permutation_test.go b/permutation_test.go new file mode 100644 index 0000000..99658f3 --- /dev/null +++ b/permutation_test.go @@ -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) + } + }) + } +}