這一問題與我先前的問題,在這裏問:如何使用遞歸獲取設定順序中的每個字符串組合?
How do I get every combination of letters using yield return and recursion?
我有一個像這樣的字符串的若干名單,從幾十的可能名單:
1: { "A", "B", "C" }
2: { "1", "2", "3" }
3: { "D", "E", "F" }
這三者是隻是作爲一個例子,用戶可以從數十個類似的列表中選擇不同數量的元素。另一個例子,這也是一個用戶一個完全有效的選擇:
25: { } // empty
4: { "%", "!", "$", "@" }
16: { "I", "a", "b", "Y" }
8: { ")", "z", "!", "8" }
我想要做的就是串可能的每個組合,同時保持名單的「秩序」。換句話說,假設我們正在查看第一個列表,那麼第一個組合將是A1D
,然後是A1E
,然後是A1F
,然後是B1D
,然後是B1E
,依此類推。根據我以前問的問題提供了答案,我寫了這方面的工作遞歸算法:
public void Tester()
{
var collection = new List { list1, list2, list3 };
var answer = GetStringCombinations(collection).ToList();
answer.ForEach(Console.WriteLine);
}
private IEnumerable<string> GetStringCombinations(List<List<string>> collection)
{
// if the collection is empty, return null to stop the recursion
if (!collection.Any())
{
yield return null;
}
// recurse down the list, selecting one letter each time
else
{
foreach (var letter in collection.First())
{
// get the collection sans the first item
var nextCollection = collection.Skip(1).ToList();
// construct the strings using yield return and recursion
foreach (var tail in GetStringCombinations(nextCollection))
{
yield return letter + tail;
}
}
}
}
然而,這種代碼依賴於yield return
正常工作。你如何在不使用關鍵字yield return
的情況下實現該算法,例如,如果我將代碼移植到ColdFusion或Ruby(假設它們沒有類似的關鍵字)?
**** sla額頭****這麼簡單明顯,但我想不起來。謝謝! –
經測試,工作正常。 –