Created
December 8, 2021 17:04
-
-
Save kgaughan/70c0d38fb998364381802f49bbc2273e to your computer and use it in GitHub Desktop.
Permuting a string in Go
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 permute | |
func fact(n int) int { | |
result := 1 | |
for i := 1; i <= n; i++ { | |
result *= i | |
} | |
return result | |
} | |
func permute(chars string) []string { | |
result := make([]string, 0, fact(len(chars))) | |
generate(&result, []rune(chars), 0, len(chars)-1) | |
return result | |
} | |
func generate(result *[]string, acc []rune, left, right int) { | |
if left == right { | |
*result = append(*result, string(acc)) | |
} else { | |
for i := left; i <= right; i++ { | |
acc[left], acc[i] = acc[i], acc[left] | |
generate(result, acc, left+1, right) | |
acc[left], acc[i] = acc[i], acc[left] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment