permute.go 976 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright (c) 2014 The mathutil Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mathutil
  5. import (
  6. "sort"
  7. )
  8. // PermutationFirst generates the first permutation of data.
  9. func PermutationFirst(data sort.Interface) {
  10. sort.Sort(data)
  11. }
  12. // PermutationNext generates the next permutation of data if possible and
  13. // return true. Return false if there is no more permutation left. Based on
  14. // the algorithm described here:
  15. // http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
  16. func PermutationNext(data sort.Interface) bool {
  17. var k, l int
  18. for k = data.Len() - 2; ; k-- { // 1.
  19. if k < 0 {
  20. return false
  21. }
  22. if data.Less(k, k+1) {
  23. break
  24. }
  25. }
  26. for l = data.Len() - 1; !data.Less(k, l); l-- { // 2.
  27. }
  28. data.Swap(k, l) // 3.
  29. for i, j := k+1, data.Len()-1; i < j; i++ { // 4.
  30. data.Swap(i, j)
  31. j--
  32. }
  33. return true
  34. }