Инструкции:Генерация перестановок с использованием полиморфных методу
Пожалуйста, напишите кусок кода, который принимает в качестве входных данных список, в котором каждый элемент является другой список, содержащий неизвестный тип и который возвращает список всех возможные списки, которые могут быть получены путем принятия одного элемента из каждого входного списка.
Например:
[[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();
}
Как я мог заставить его работать с полиморфного метода, который возвращает общий список?
«Полиморфный метод» означает «общий метод» или что-то еще в вашем посте? (Я не вижу «полиморфизма» в выборке) ... –
@AlexeiLevenkov - Я думаю, что это означает «общий метод». Но только гадать. – NomadTraveler
«любого типа» определенно кричит дженерики, но они терминология, которую они использовали, нечеткая. – jdphenix