Last active
August 29, 2015 14:07
-
-
Save chrisport/381b4f56eec514e5d8b4 to your computer and use it in GitHub Desktop.
Generate Permutations of String in Golang
This file contains 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 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