Created
July 4, 2016 22:50
-
-
Save Fhernd/ef8ba8c366ee73c18339f0fd20acfada to your computer and use it in GitHub Desktop.
LINQ recipe to generate for a given string literal. [OrtizOL]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generates partial permutations for a given string: | |
private HashSet<string> GeneratePartialPermutation(string word) | |
{ | |
return new HashSet<string>(Enumerable.Range(0, word.Length) | |
.Select(i => word.Remove(i, 1).Insert(0, word[i].ToString()))); | |
} | |
// Entry point for the LINQ recipe: | |
void Main() | |
{ | |
// Stores all the permutations computed in HashSet data structure. | |
// It also generates the first partial permutations: | |
HashSet<string> perms = GeneratePartialPermutation("abcd"); | |
// Generates permutations by traversing all possible permutations of | |
// the given string -"abcd"-: | |
Enumerable.Range(0, 2) | |
.ToList() | |
.ForEach | |
( | |
c => | |
{ | |
// Permutations in forward direction: | |
Enumerable.Range(0, perms.Count()) | |
.ToList() | |
.ForEach | |
( | |
i => GeneratePartialPermutation( | |
perms.ElementAt(i)) | |
.ToList() | |
.ForEach(p => perms.Add(p)) | |
); | |
// Permutations in reverse direction: | |
Enumerable.Range(0, perms.Count()) | |
.ToList() | |
.ForEach | |
( | |
i => GeneratePartialPermutation(new String | |
(perms.ElementAt(i).ToCharArray() | |
.Reverse().ToArray()) | |
) | |
.ToList().ForEach(p => perms.Add(p))); | |
} | |
); | |
// Displays all permutations: | |
perms.OrderBy(p => p).Dump("Permutations of 'abcd'"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment