Nom*_*ler 8 c# polymorphism permutation
说明 :
请编写一段代码作为输入列表,其中每个元素是另一个包含未知类型的列表,并返回可以通过从每个输入列表中取一个元素获得的所有可能列表的列表.
例如:
[[1,2],[3,4]],应该返回:[[1,3],[1,4],[2,3],[2,4]].
[['1'],['2'],['3','4']]应该返回[['1','2','3'],['1','2', '4'].
我的代码:
public static void Main(string[] args)
{
//Create a list of lists of objects.
var collections = new List<List<object>>();
collections.Add(new List<object> { 1, 5, 3 });
collections.Add(new List<object> { 7, 9 });
collections.Add(new List<object> { "a", "b" });
//Get all the possible permutations
var combinations = GetPermutations(collections);
//Loop through the results and display them in console
foreach (var result in combinations)
{
result.ForEach(item => Console.Write(item + " "));
Console.WriteLine();
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static List<List<object>> GetPermutations(List<List<object>> collections)
{
List<List<object>> permutations = new List<List<object>>();
//Check if the input list has any data, else return the empty list.
if (collections.Count <= 0)
return permutations;
//Add the values of the first set to the empty List<List<object>>
//permutations list
foreach (var value in collections[0])
permutations.Add(new List<object> { value });
/* Skip the first set of List<List<object>> collections as it was
* already added to the permutations list, and loop through the
* remaining sets. For each set, call the AppendValues function
* to append each value in the set to the permuations list.
* */
foreach (var set in collections.Skip(1))
permutations = AppendNewValues(permutations, set);
return permutations;
}
private static List<List<object>> AppendNewValues(List<List<object>> permutations, List<object> set)
{
//Loop through the values in the set and append them to each of the
//list of permutations calculated so far.
var newCombinations = from additional in set
from value in permutations
select new List<object>(value) { additional };
return newCombinations.ToList();
}
Run Code Online (Sandbox Code Playgroud)
我如何使用返回通用列表的多态方法?
请编写一段代码,将一个列表作为输入,其中每个元素都是另一个包含未知类型的列表,并返回所有可能列表的列表,这些列表可以通过从每个输入列表中获取一个元素来获得。
我会要求澄清,比如“那么你的意思是通用方法?”
说到多态性,他们可能只能编写一种方法并以任何任意类型调用它,例如:
public static IList<IList<T>> GetPermutations<T>(IList<IList<T>> inputLists) {
if (inputLists.Count < 2) {
// special case.
}
return _permutationHelper(0, inputLists);
}
private static IList<IList<T>> _permutationHelper<T>(int i, IList<IList<T>> inputLists) {
IList<IList<T>> returnValue = new List<IList<T>>();
if (i == inputLists.Count) {
returnValue.Add(new List<T>());
} else {
foreach (var t in inputLists[i]) {
foreach (var list in _permutationHelper(i + 1, inputLists)) {
list.Add(t);
returnValue.Add(list);
}
}
}
return returnValue;
}
Run Code Online (Sandbox Code Playgroud)
确实,您的实现在运行时允许任意类型,但它失去了类型安全性。鉴于它是 C# 中的实现,类型安全是一项要求是一个安全的猜测 - 但问一下也没什么坏处。
另一件值得注意的事情 - 他们可能只是说他们正在寻找给定列表的笛卡尔积。