Last active
May 19, 2022 12:29
-
-
Save balacode/ff456d2e5854f2803790cc0a06ae5769 to your computer and use it in GitHub Desktop.
PermuteStrings() - fn to generate a string array of all combinations of input string slices, maintaining order
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
// ----------------------------------------------------------------------------- | |
// (c) [email protected] License: MIT | |
// :v: 2018-03-18 23:55:24 [permute_strings.go] | |
// ----------------------------------------------------------------------------- | |
package main | |
import "bytes" // standard | |
import "fmt" // standard | |
import "testing" // standard | |
func PermuteStrings(parts ...[]string) (ret []string) { | |
{ | |
var n = 1 | |
for _, ar := range parts { | |
n *= len(ar) | |
} | |
ret = make([]string, 0, n) | |
} | |
var at = make([]int, len(parts)) | |
var buf bytes.Buffer | |
loop: | |
for { | |
// increment position counters | |
for i := len(parts) - 1; i >= 0; i-- { | |
if at[i] > 0 && at[i] >= len(parts[i]) { | |
if i == 0 || (i == 1 && at[i-1] == len(parts[0])-1) { | |
break loop | |
} | |
at[i] = 0 | |
at[i-1]++ | |
} | |
} | |
// construct permutated string | |
buf.Reset() | |
for i, ar := range parts { | |
var p = at[i] | |
if p >= 0 && p < len(ar) { | |
buf.WriteString(ar[p]) | |
} | |
} | |
ret = append(ret, buf.String()) | |
at[len(parts)-1]++ | |
} | |
return ret | |
} | |
// go test --run Test_PermuteStrings_ | |
func Test_PermuteStrings_(t *testing.T) { | |
var ar = PermuteStrings( | |
[]string{"11", "22", "33"}, | |
[]string{}, | |
[]string{"AA", "BB", "CC"}, | |
[]string{"XX", "YY"}, | |
) | |
fmt.Println("RESULT:") | |
for _, s := range ar { | |
fmt.Println("-->", s) | |
} | |
} | |
/* | |
RESULT: | |
--> 11AAXX | |
--> 11AAYY | |
--> 11BBXX | |
--> 11BBYY | |
--> 11CCXX | |
--> 11CCYY | |
--> 22AAXX | |
--> 22AAYY | |
--> 22BBXX | |
--> 22BBYY | |
--> 22CCXX | |
--> 22CCYY | |
--> 33AAXX | |
--> 33AAYY | |
--> 33BBXX | |
--> 33BBYY | |
--> 33CCXX | |
--> 33CCYY | |
*/ | |
//end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment