是否可以創建一些Linq來生成包含一系列數字的所有可能組合的List?Linq中的組合發生器
如果輸入「21」,它會產生與元素的列表:
list[0] = "21"
list[1] = "22"
list[2] = "11"
list[3] = "12"
(不nessesarily順序)
我知道你可以使用範圍做這樣的事情:
List<char> letterRange = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToList(); //97 - 122 + 1 = 26 letters/iterations
它從az生成字母表。但我似乎無法將這些知識轉化爲組合生成器
我已經能夠用下面的代碼弄明白了,但它看起來太笨重了,我相信它可以用幾行來完成。它確實感覺我是一個糟糕的解決方案。
想象我呼籲GetAllCombinations("4321")
如果它可以幫助
public static String[] GetAllCombinations(String s)
{
var combinations = new string[PossibleCombinations(s.Length)];
int n = PossibleCombinations(s.Length - 1);
for (int i = 0; i < s.Length; i++)
{
String sub;
String[] subs;
if (i == 0)
{
sub = s.Substring(1); //Get the first number
}
else if (i == s.Length - 1)
{
sub = s.Substring(0, s.Length - 1);
}
else
{
sub = s.Substring(0, i) + s.Substring(i + 1);
}
subs = GetAllCombinations(sub);
for (int j = 0; j < subs.Length; j++)
{
combinations[i * n + j] = s[i] + subs[j];
}
}
return combinations;
}
public static int PossibleCombinations(int n) //Combination possibilities. e.g 1-2-3-4 have 24 different combinations
{
int result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
+1我不認爲這個答案有足夠的提議 – 2011-06-08 09:37:11
只需要注意,這個函數並沒有做什麼問題。 (它產生`{「12」,「21」},缺少``11「和`」22「`)。我只能假設提問者確實設法將它調整爲有用的東西。 – Rawling 2012-07-17 08:42:58