File: permutation.go

package info (click to toggle)
golang-github-thoas-go-funk 0.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 504 kB
  • sloc: makefile: 10
file content (29 lines) | stat: -rw-r--r-- 496 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
}