我有一個整數串列:
List <int> allPossibleValues;
密碼長度:
int passwordLength = 2;
我應該使用串列中的整數生成密碼的所有可能組合:
List <int> allPossibleValues = new List<int>() { 1, 2, 4};
int passwordLength = 2;
預期結果:
List<string> {
"11", "22", "44", "12", "21", "14", "41", "24", "42"
};
如何創建邏輯來實作這一點?
uj5u.com熱心網友回復:
好吧,你可以這樣寫:
代碼:
using System.Linq;
...
// Let's do it a bit more general - <T> - and enumerate any items of alphabet
private static IEnumerable<string> Passwords<T>(List<T> alphabet, int size) {
int[] current = new int[size];
do {
yield return string.Concat(current.Select(i => alphabet[i]));
for (int i = 0; i < current.Length; i)
if ((current[i] = (current[i] 1) % alphabet.Count) != 0)
break;
}
while (!current.All(i => i == 0));
}
演示:
List <int> allPossibleValues = new List<int>() { 1, 2, 4};
int passwordLength = 2;
string[] passwords = Passwords(allPossibleValues, passwordLength).ToArray();
var report = string.Join(", ", passwords);
Console.Write(report);
結果:
11, 21, 41, 12, 22, 42, 14, 24, 44
uj5u.com熱心網友回復:
您可以只使用兩個 for 回圈來遍歷您的 Input 串列兩次,組合這些值并將組合的值添加到一個新串列中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397988.html
上一篇:如何在Linq中將行轉換為列
下一篇:以一致的格式獲取日期