Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created February 5, 2017 23:52
Show Gist options
  • Save Fhernd/c531ad4cc479488abad5619ea305067d to your computer and use it in GitHub Desktop.
Save Fhernd/c531ad4cc479488abad5619ea305067d to your computer and use it in GitHub Desktop.
Generador de permutaciones con programación funcional.
private HashSet<string> GenerarPermutacionParcial(string word)
{
return new HashSet<string>(
Enumerable.Range(0, word.Length)
.Select(i => word.Remove(i, 1).Insert(0, word[i].ToString())));
} // abcd, bacd, cacd, dabc
void Main()
{
// Generación de las primeras permutaciones parciales:
HashSet<string> perms = GenerarPermutacionParcial("abcd");
Enumerable.Range(0, 2)
.ToList()
.ForEach(
c =>
{
// Permutaciones en sentido izquierda derecha:
Enumerable.Range(0, perms.Count())
.ToList()
.ForEach
(
i => GenerarPermutacionParcial(
perms.ElementAt(i))
.ToList()
.ForEach(p => perms.Add(p))
);
// Permutaciones en sentido contrario:
Enumerable.Range(0, perms.Count())
.ToList()
.ForEach
(
i => GenerarPermutacionParcial(
new String(perms.ElementAt(i).ToCharArray()
.Reverse().ToArray())
)
.ToList().ForEach(p => perms.Add(p)));
}
);
perms.OrderBy(p => p).Dump("Permutaciones de 'abcd'");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment