Advertisement
Fhernd

VT2.14-Generar-Permutaciones.linq

Feb 5th, 2017
40,112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. private HashSet<string> GenerarPermutacionParcial(string word)
  2. {
  3.     return new HashSet<string>(
  4.         Enumerable.Range(0, word.Length)
  5.         .Select(i => word.Remove(i, 1).Insert(0, word[i].ToString())));
  6. } // abcd, bacd, cacd, dabc
  7.  
  8. void Main()
  9. {
  10.     // Generación de las primeras permutaciones parciales:
  11.     HashSet<string> perms = GenerarPermutacionParcial("abcd");
  12.    
  13.     Enumerable.Range(0, 2)
  14.         .ToList()
  15.         .ForEach(
  16.             c =>
  17.             {
  18.                 // Permutaciones en sentido izquierda derecha:
  19.                 Enumerable.Range(0, perms.Count())
  20.                 .ToList()
  21.                 .ForEach
  22.                 (
  23.                     i => GenerarPermutacionParcial(
  24.                         perms.ElementAt(i))
  25.                         .ToList()
  26.                         .ForEach(p => perms.Add(p))
  27.                 );
  28.  
  29.                 // Permutaciones en sentido contrario:
  30.                 Enumerable.Range(0, perms.Count())
  31.                 .ToList()
  32.                 .ForEach
  33.                 (
  34.                     i => GenerarPermutacionParcial(
  35.                         new String(perms.ElementAt(i).ToCharArray()
  36.                                         .Reverse().ToArray())
  37.                 )
  38.                 .ToList().ForEach(p => perms.Add(p)));
  39.             }
  40.         );
  41.        
  42.         perms.OrderBy(p => p).Dump("Permutaciones de 'abcd'");
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement