Created
August 8, 2019 21:01
-
-
Save teivah/8131cf49d8092bcd88dd82a17f21a2a9 to your computer and use it in GitHub Desktop.
How to display all the possible permutations of 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
func printAllPermutations(s string) { | |
permute(s, 0, len(s)-1) | |
} | |
func permute(s string, left, right int) { | |
if left == right { | |
fmt.Printf("%s\n", s) | |
} | |
for i := left; i <= right; i++ { | |
s = swap(s, left, i) | |
permute(s, left+1, right) | |
s = swap(s, left, i) | |
} | |
} | |
func swap(s string, i1, i2 int) string { | |
r := []rune(s) | |
tmp := r[i1] | |
r[i1] = r[i2] | |
r[i2] = tmp | |
return string(r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment