Last active
February 4, 2022 13:21
-
-
Save fatihdumanli/5e7a577f33976a29d7200ffba935f1d3 to your computer and use it in GitHub Desktop.
Finding all permutations of a 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 main | |
import ( | |
"fmt" | |
"strings" | |
) | |
var result []string | |
func main() { | |
permuteString("", "golang") | |
fmt.Printf("%d permutations found.\n", len(result)) | |
} | |
func permuteString(prefix string, rem string) { | |
if len(rem) == 0 { | |
result = append(result, prefix) | |
return | |
} | |
for i := 0; i < len(rem); i++ { | |
//swap ith char with rem[0] | |
//and trigger the next recursion. | |
s := swap(rem, 0, i) | |
p := prefix + string(s[0]) | |
newRem := s[1:] | |
permuteString(p, newRem) | |
} | |
} | |
func swap(s string, i int, j int) string { | |
ith := s[i] | |
jth := s[j] | |
var sb strings.Builder | |
for m := 0; m < len(s); m++ { | |
if m == i { | |
sb.WriteByte(jth) | |
continue | |
} | |
if m == j { | |
sb.WriteByte(ith) | |
continue | |
} | |
sb.WriteByte(s[m]) | |
} | |
return sb.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment