v1:
package main import ( "fmt" ) func permutate(collection [][]rune, plus rune) (newCollection [][]rune) { if len(collection) == 0 { newCollection = [][]rune{{plus}} return } newCollection = make([][]rune, 0) for _, orignalArr := range collection { oldLength := len(orignalArr) newLength := oldLength + 1 for i := 0; i < newLength; i++ { newArr := make([]rune, newLength) newArr[i] = plus for orignalKey, originalValue := range orignalArr { var newKey int if orignalKey < i { newKey = orignalKey } else { newKey = orignalKey + 1 } newArr[newKey] = originalValue } newCollection = append(newCollection, newArr) } } return } func getAllPermutations(s string) []string { arr := []rune(s) collection := [][]rune{} for _, e := range arr { collection = permutate(collection, e) } strCollection := make([]string, 0, len(collection)) for _, charArr := range collection { strCollection = append(strCollection, string(charArr)) } return strCollection } func main() { fmt.Println(getAllPermutations("abcd")) }
v2:
package main import ( "fmt" ) func processPermutations(s string, procedure func(string)) { elements := []rune(s) length := len(elements) var permutate func([]rune, int) permutate = func(elements []rune, from int) { if from == length-1 { procedure(string(elements)) } var elementsCopy []rune = make([]rune, length) for i := from; i < length; i++ { copy(elementsCopy, elements) elementsCopy[from], elementsCopy[i] = elementsCopy[i], elementsCopy[from] permutate(elementsCopy, from+1) } } permutate(elements, 0) } func main() { processPermutations("abcd", func(s string) { fmt.Println(s) }) }