Le istruzioni:generare permutazioni usando il metodo polimorfico
Si prega di scrivere un pezzo di codice che prende come input una lista in cui ogni elemento è un altro elenco contenente un tipo sconosciuto, e che restituisce un elenco di tutti i liste possibili che possono essere ottenute prendendo un elemento da ciascuno degli elenchi di input.
Ad esempio:
[[1, 2], [3, 4]], dovrebbe restituire: [[1, 3], [1, 4], [2, 3], [2, 4]].
[['1'], ['2'], ['3', '4']], dovrebbe restituire [['1', '2', '3'], ['1', '2', '4']].
Il mio codice:
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();
}
Come potrei farlo funzionare con il metodo polimorfico che restituisce un elenco generico?
Il "metodo polimorfico" indica "metodo generico" o qualcos'altro nel post? (Non vedo "polimorfismo" nel campione) ... –
@AlexeiLevenkov - Penso che significhi "metodo generico". Solo indovinando qui però. – NomadTraveler
"di qualsiasi tipo" sicuramente urla i generici, ma la loro terminologia utilizzata è sfocata. – jdphenix