Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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'");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement