Skip to content

Instantly share code, notes, and snippets.

@teivah
Created August 8, 2019 21:01
Show Gist options
  • Save teivah/8131cf49d8092bcd88dd82a17f21a2a9 to your computer and use it in GitHub Desktop.
Save teivah/8131cf49d8092bcd88dd82a17f21a2a9 to your computer and use it in GitHub Desktop.
How to display all the possible permutations of a string in Go?
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