我在C#中看到了幾個字符串變體的實現,但它們都沒有對它們的長度有任何限制。不幸的是,我無法修改它們來實現我的目標,例如從字符串中生成特定長度的所有變體
爲:
string = "ABCD" and variationLength = 2
生成新的字符串:
AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC
我正在尋找的正是這種Python的和itertools.permutations實現,但在C#。 (https://docs.python.org/3/library/itertools.html#itertools.permutations)
在C#中有類似的東西嗎?如果不是,那麼實現它的最簡單方法是什麼?
Edit_2: 到目前爲止,我想出了一個主意,列出定字符串的所有獨特的字符,然後讓變化了出來
static void PrintAllKLengthPerm(string str, int k)
{
int n = str.Length;
PrintAllKLengthPermRec(str, "", n, k);
}
// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
// Base case: k is 0, print prefix
if (k == 0)
{
Console.WriteLine(prefix);
return;
}
// One by one add all characters from str and recursively
// call for k equals to k-1
for (int i = 0; i < n; ++i)
{
// Next character of input added
String newPrefix = prefix + str[i];
// k is decreased, because we have added a new character
PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
}
}
static void Main(string[] args)
{
string str = "ABCD";
int permLen = 2;
//get all unique characters in string
string uniqStr = new String(str.Distinct().ToArray());
// Print all possible strings of length permLen out of uniqStr characters
PrintAllKLengthPerm(uniqStr, permLen);
}
但是我正在尋找更優化,有效地解決
你嘗試過這麼遠嗎? – Ani
請顯示您的工作。你試過什麼了? – Soviut
@Soviut編輯.. –