Last active
August 29, 2015 14:17
-
-
Save onema/4b3a240d914f6abcf153 to your computer and use it in GitHub Desktop.
Heap's algorithm to generate permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/** | |
* Word permutations using Heap's algorithm | |
* http://en.wikipedia.org/wiki/Heap%27s_algorithm | |
*/ | |
import ( | |
"fmt" | |
"strings" | |
"bytes" | |
) | |
/** | |
* Wrapper function to convert string into an array and get it's length | |
*/ | |
func permutations(word string) string { | |
wordArray := strings.Fields(word) | |
generatedString := generate(len(wordArray)-1, wordArray) | |
return generatedString | |
} | |
/** | |
* Main algorithm | |
*/ | |
func generate (n int, A []string) string { | |
var generatedString string | |
var buffer bytes.Buffer | |
if n == 0 { | |
buffer.WriteString(strings.Join(A, ", ")) | |
buffer.WriteString("\n") | |
return buffer.String() | |
} else { | |
for i := 0; i <= n; i++ { | |
buffer.WriteString(generatedString) | |
buffer.WriteString(generate(n-1, A)) | |
// j = i if n is not odd. | |
j := i | |
// If n is odd set j to zero | |
if n % 2 != 0{ | |
j = 0 | |
} | |
A = swap(A, j, n) | |
} | |
return buffer.String() | |
} | |
} | |
/** | |
* Swap two elements in A i and n | |
*/ | |
func swap (A []string, j int, n int) []string { | |
// swap | |
aj := A[j] | |
an := A[n] | |
A[j] = an | |
A[n] = aj | |
return A | |
} | |
func main() { | |
fmt.Println(permutations("foo bar baz")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the generated output will look like this: