Generatore di combinazioni in Linq
-
13-09-2019 - |
Domanda
È possibile creare qualche Linq che generi una lista contenente tutte le possibili combinazioni di una serie di numeri??
Se inserisci "21" verrà generato un elenco con gli elementi:
list[0] = "21"
list[1] = "22"
list[2] = "11"
list[3] = "12"
(Non necessariamente in quest'ordine)
Capisco che puoi utilizzare l'intervallo per fare cose come:
List<char> letterRange = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToList(); //97 - 122 + 1 = 26 letters/iterations
Che genera l'alfabeto dalla a-z.Ma non riesco a trasferire questa conoscenza per creare un generatore di combinazioni
Sono riuscito a capirlo con il seguente codice, ma sembra troppo ingombrante e sono sicuro che può essere fatto con poche righe.Sembra davvero che io abbia preso una pessima soluzione.
Immagina di aver chiamato GetAllCombinations("4321")
se aiuta
public static String[] GetAllCombinations(String s)
{
var combinations = new string[PossibleCombinations(s.Length)];
int n = PossibleCombinations(s.Length - 1);
for (int i = 0; i < s.Length; i++)
{
String sub;
String[] subs;
if (i == 0)
{
sub = s.Substring(1); //Get the first number
}
else if (i == s.Length - 1)
{
sub = s.Substring(0, s.Length - 1);
}
else
{
sub = s.Substring(0, i) + s.Substring(i + 1);
}
subs = GetAllCombinations(sub);
for (int j = 0; j < subs.Length; j++)
{
combinations[i * n + j] = s[i] + subs[j];
}
}
return combinations;
}
public static int PossibleCombinations(int n) //Combination possibilities. e.g 1-2-3-4 have 24 different combinations
{
int result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
Soluzione
Per quello che vale, prova qualcosa del genere:
public static IEnumerable<string> GetPermutations(string s)
{
if (s.Length > 1)
return from ch in s
from permutation in GetPermutations(s.Remove(s.IndexOf(ch), 1))
select string.Format("{0}{1}", ch, permutation);
else
return new string[] { s };
}
Altri suggerimenti
Per il record:La risposta di Josh in modo generico:
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items) {
if (items.Count() > 1) {
return items.SelectMany(item => GetPermutations(items.Where(i => !i.Equals(item))),
(item, permutation) => new[] { item }.Concat(permutation));
} else {
return new[] {items};
}
}
Ecco la mia funzione di permutazione e combinazione utilizzando Linq
public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource item)
{
if (source == null)
throw new ArgumentNullException("source");
yield return item;
foreach (var element in source)
yield return element;
}
public static IEnumerable<IEnumerable<TSource>> Permutate<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
throw new ArgumentNullException("source");
var list = source.ToList();
if (list.Count > 1)
return from s in list
from p in Permutate(list.Take(list.IndexOf(s)).Concat(list.Skip(list.IndexOf(s) + 1)))
select p.Prepend(s);
return new[] { list };
}
public static IEnumerable<IEnumerable<TSource>> Combinate<TSource>(this IEnumerable<TSource> source, int k)
{
if (source == null)
throw new ArgumentNullException("source");
var list = source.ToList();
if (k > list.Count)
throw new ArgumentOutOfRangeException("k");
if (k == 0)
yield return Enumerable.Empty<TSource>();
foreach (var l in list)
foreach (var c in Combinate(list.Skip(list.Count - k - 2), k - 1))
yield return c.Prepend(l);
}
Per l'alfabeto del DNA "A", "C", "G", "T":
var dna = new[] {'A', 'C', 'G', 'T'};
foreach (var p in dna.Permutate())
Console.WriteLine(String.Concat(p));
dà
ACGT ACTG AGCT AGTC ATCG ATGC CAGT CATG CGAT CGTA CTAG CTGA GACT GATC GCAT GCTA GTAC GTCA TACG TAGC TCAG TCGA TGAC TGCA
e le combinazioni (k = 2) dell'alfabeto del DNA
foreach (var c in dna.Combinate(2))
Console.WriteLine(String.Concat(c));
Sono
AA AC AG AT CA CC CG CT GA GC GG GT TA TC TG TT
Quello che stai cercando sono in realtà permutazioni.In breve, permutazioni significa che l'ordine è rilevante (cioè, 12 è diverso da 21) mentre una combinazione significa che l'ordine è irrilevante (12 e 21 sono equivalenti).Per ulteriori informazioni, vedere Wikipedia.
Vedere questo filo.
Per quanto riguarda il fare è in puro LINQ, sembra come usare LINQ per il gusto di usare LINQ.
Come altri hanno sottolineato, le soluzioni in questa pagina genereranno duplicati se uno qualsiasi degli elementi è uguale.L'estensione Distinct() li rimuoverà, ma non è molto scalabile poiché di solito comporterà comunque l'attraversamento dell'intero albero di ricerca.Ridurrai considerevolmente lo spazio di ricerca invocandolo durante l'attraversamento:
private static IEnumerable<string> Permute(string str)
{
if (str.Length == 0)
yield return "";
else foreach (var index in str.Distinct().Select(c => str.IndexOf(c)))
foreach (var p in Permute(str.Remove(index, 1)))
yield return str[index] + p;
}
Per la stringa di esempio "bananabana" ciò si traduce in 8.294 nodi visitati, rispetto ai 9.864.101 visitati quando non si esegue l'estrazione trasversale.
È possibile utilizzare questa estensione LINQ Permute:
foreach (var value in Enumerable.Range(1,3).Permute())
Console.WriteLine(String.Join(",", value));
Il che si traduce in questo:
1,1,1
1,1,2
1,1,3
1,2,1
1,2,2
1,2,3
1,3,1
1,3,2
1,3,3
2,1,1
2,1,2
2,1,3
2,2,1
2,2,2
2,2,3
2,3,1
...
Facoltativamente è possibile specificare il numero di permutazioni
foreach (var value in Enumerable.Range(1,2).Permute(4))
Console.WriteLine(String.Join(",", value));
Risultati:
1,1,1,1
1,1,1,2
1,1,2,1
1,1,2,2
1,2,1,1
1,2,1,2
1,2,2,1
1,2,2,2
2,1,1,1
2,1,1,2
2,1,2,1
2,1,2,2
2,2,1,1
2,2,1,2
2,2,2,1
2,2,2,2
Classe di estensione da aggiungere:
public static class IEnumberableExtensions
{
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> values) => values.SelectMany(x => Permute(new[] { new[] { x } }, values, values.Count() - 1));
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> values, int permutations) => values.SelectMany(x => Permute(new[] { new[] { x } }, values, permutations - 1));
private static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<IEnumerable<T>> current, IEnumerable<T> values, int count) => (count == 1) ? Permute(current, values) : Permute(Permute(current, values), values, --count);
private static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<IEnumerable<T>> current, IEnumerable<T> values) => current.SelectMany(x => values.Select(y => x.Concat(new[] { y })));
}