2011-02-27 33 views
6

Tengo 10 palabras. ¿Cómo puedo obtener todas las combinaciones posibles de 5 palabras (n=10, k=5)? El pedido no importa.Combinaciones de palabras sin repetición

Por ejemplo: "A", "B", "C", if k=2 (n=3 in this case), le gustaría AB, BC y AC. Quizás conozcas algún código útil o ejemplo.

P.S. Lo siento si no estoy bien porque no sé inglés muy bien.

Respuesta

15

Lo que intenta hacer es obtener todas las permutaciones de una colección.

Aquí es el fragmento de código:

static void Main(string[] args) 
{ 
    var list = new List<string> { "a", "b", "c", "d", "e" }; 
    var result = GetPermutations(list, 3); 
    foreach (var perm in result) 
    { 
     foreach (var c in perm) 
     { 
      Console.Write(c + " "); 
     } 
     Console.WriteLine(); 
    } 
    Console.ReadKey(); 
} 

static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int count) 
{ 
    int i = 0; 
    foreach (var item in items) 
    { 
     if (count == 1) 
      yield return new T[] { item }; 
     else 
     { 
      foreach (var result in GetPermutations(items.Skip(i + 1), count - 1)) 
       yield return new T[] { item }.Concat(result); 
     } 

     ++i; 
    } 
} 

Salidas:

a b c 
a b d 
a b e 
a c d 
a c e 
a d e 
b c d 
b c e 
b d e 
c d e 
+4

Para ser más matemáticamente correcto. Usted llama a esto combinaciones (el orden no es importante) sin repetición (un artículo puede ocurrir como máximo 1 vez o menos). https://www.mathsisfun.com/combinatorics/combinations-permutations.html –

+0

¿No implica "como máximo 1 vez" "o menos"? – shiggity

0

Qué pasa con un mayor funcionalismo l de solución

var list = new List<string> { "a", "b", "c", "d", "e" }; 
GetAllCombinations(list).OrderBy(_ => _).ToList().ForEach(Console.WriteLine); 


static IEnumerable<string> GetAllCombinations(IEnumerable<string> list) 
{ 
    return list.SelectMany(mainItem => list.Where(otherItem => !otherItem.Equals(mainItem)) 
           .Select(otherItem => mainItem + otherItem)); 
} 

Ouput:

ab 
ac 
ad 
ae 
ba 
bc 
bd 
be 
ca 
cb 
cd 
ce 
da 
db 
dc 
de 
ea 
eb 
ec 
ed 
Cuestiones relacionadas