Advertisement
Fhernd

PowerSet.cs

Jul 6th, 2016
738
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 KB | None | 0 0
  1. // Generates partial permutations for a given string:
  2. private HashSet<string> GeneratePartialPermutation(string word)
  3. {
  4.     return new HashSet<string>(Enumerable.Range(0, word.Length)
  5.         .Select(i => word.Remove(i, 1).Insert(0, word[i].ToString())));
  6. }
  7.  
  8. // Entry point for the recipe execution:
  9. void Main()
  10. {
  11.     // Word with all characters to compute its power set:
  12.     string word = "abc";
  13.    
  14.     // Create a set with the n-initial permutations:
  15.     HashSet<string> perms = GeneratePartialPermutation(word);
  16.    
  17.     // Produces all the element pairs for each partial permutation
  18.     // (e.g., for the word 'abc' there are three element pairs
  19.     // {"a", "bc"}, {"ab", "c"}, {"abc"}:
  20.     Enumerable.Range(0, word.Length)
  21.         .ToList()
  22.         .ForEach(x =>
  23.             Enumerable.Range(0, word.Length)
  24.                 .ToList()
  25.                 .ForEach(z =>
  26.                 {
  27.                     // First element pair:
  28.                     perms.Add(perms.ElementAt(x).Substring(0, z));
  29.                     // Second element pair:
  30.                     perms.Add(perms.ElementAt(x).Substring(z+1));
  31.                 }));
  32.    
  33.     // Sorts and removes duplicates from all the generated element pairs:
  34.     perms.Select(p => new string(p.ToCharArray()
  35.         .OrderBy(x => x)
  36.         .ToArray()))
  37.         .Distinct()
  38.         .OrderBy(p => p.Length)
  39.         .Dump("Power set of 'abc'");
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement