Skip to content

Instantly share code, notes, and snippets.

@chrisport
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisport/381b4f56eec514e5d8b4 to your computer and use it in GitHub Desktop.
Save chrisport/381b4f56eec514e5d8b4 to your computer and use it in GitHub Desktop.
Generate Permutations of String in Golang
package permutations
func merge(ins []rune, c rune) (result []string) {
for i := 0; i <= len(ins); i++ {
result = append(result, string(ins[:i])+string(c)+string(ins[i:]))
}
return
}
func permutations(input string) []string {
if len(input) == 1 {
return []string{input}
}
runes := []rune(input)
subPermutations := permutations(string(runes[0:len(input) - 1]))
result := []string{}
for _, s := range subPermutations {
result = append(result, merge([]rune(s), runes[len(input)-1])...)
}
return result
}
func permutationsTailRecursive(input string) []string {
var helper func(input []rune, previousResult []string) []string
helper = func(input []rune, previousResult []string) []string{
if len(input) == 0 {
return previousResult
}else {
newResult := []string{}
for _, element := range previousResult {
newResult = append(newResult, merge([]rune(element), input[0])...)
}
return helper(input[1:], newResult)
}
}
runes := []rune(input)
return helper(runes[1:], []string{string(runes[0])})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment