Heap's Algorithm for generating all permutations of n objects
(out chan []string, n int)
| 11 | |
| 12 | // Heap's Algorithm for generating all permutations of n objects |
| 13 | func Heaps(out chan []string, n int) { |
| 14 | elementSetCh := make(chan []string) |
| 15 | go GenerateElementSet(elementSetCh, n) |
| 16 | elementSet := <-elementSetCh |
| 17 | |
| 18 | var recursiveGenerate func([]string, int, []string) |
| 19 | var permutations []string |
| 20 | recursiveGenerate = func(previousIteration []string, n int, elements []string) { |
| 21 | if n == 1 { |
| 22 | permutations = append(permutations, strings.Join(elements, "")) |
| 23 | } else { |
| 24 | for i := 0; i < n; i++ { |
| 25 | recursiveGenerate(previousIteration, n-1, elements) |
| 26 | if n%2 == 1 { |
| 27 | tmp := elements[i] |
| 28 | elements[i] = elements[n-1] |
| 29 | elements[n-1] = tmp |
| 30 | } else { |
| 31 | tmp := elements[0] |
| 32 | elements[0] = elements[n-1] |
| 33 | elements[n-1] = tmp |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | recursiveGenerate(permutations, n, elementSet) |
| 39 | out <- permutations |
| 40 | } |
| 41 | |
| 42 | func GenerateElementSet(out chan []string, n int) { |
| 43 | elementSet := make([]string, n) |