Die Anweisungen:Generieren Permutationen unter Verwendung polymorphen Methode
Schreiben ein Stück Code, das eine Liste als eine Eingabe in dem nimmt jedes Element eine andere Liste ist eine unbekannte Art enthalten und die gibt eine Liste aller mögliche Listen, die erhalten werden können, indem ein Element aus jeder der Eingangslisten genommen wird.
Zum Beispiel:
[[1, 2], [3, 4]] sollte zurückgeben: [[1, 3], [1, 4], [2, 3], [2, 4]].
[['1'], ['2'], ['3', '4']], sollte [['1', '2', '3'], ['1', '2', '4']].
Mein Code:
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();
}
Wie konnte ich es mit polymorphen Methode funktioniert, die eine generische Liste zurückgibt?
Bedeutet "polymorphe Methode" "generische Methode" oder etwas anderes in Ihrem Beitrag? (Ich sehe nicht "Polymorphismus" in der Probe) ... –
@AlexeiLevenkov - Ich denke, es bedeutet "generische Methode". Ich rate aber nur hier. – NomadTraveler
"von jeder Art" schreit auf jeden Fall Generika, aber sie sind Terminologie, die sie verwendet wird, ist unscharf. – jdphenix