Advertisement
Guest User

Benchmark for IsStringMadeOf

a guest
Oct 13th, 2014
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. //Tested with 7289505 random inputs.   
  2.  
  3.     // 44 seconds
  4.     public static bool IsStringMadeOf1(this string str, string from)
  5.         {
  6.             if (str.Length > from.Length) return false;
  7.  
  8.             for (int i = 0; i < str.Length; i++)
  9.             {
  10.                 int index = from.IndexOf(str[i]);
  11.                 if (index != -1)
  12.                 {
  13.                     from = from.Remove(index, 1);
  14.                 }
  15.                 else
  16.                 {
  17.                     return false;
  18.                 }
  19.             }
  20.             return true;
  21.         }
  22.  
  23.     // 59 seconds
  24.     public static bool IsStringMadeOf2(this string str, string from)
  25.         {
  26.             if (str.Length > from.Length) return false;
  27.  
  28.             Dictionary<char, int> seqSource = str.GroupBy(c => c)
  29.                 .ToDictionary(key => key.Key, value => value.Count());
  30.  
  31.             Dictionary<char, int> seqTest = from.GroupBy(c => c)
  32.                 .ToDictionary(key => key.Key, value => value.Count());
  33.  
  34.             int count;
  35.  
  36.             foreach (var kvp in seqSource)
  37.             {
  38.                 if (!seqTest.TryGetValue(kvp.Key, out count) || kvp.Value > count) return false;
  39.             }
  40.  
  41.             return true;
  42.         }
  43.    
  44.     // 45 seconds
  45.     public unsafe static bool IsStringMadeOf3(this string str, string from)
  46.         {
  47.             if (str.Length > from.Length) return false;
  48.  
  49.             var copy = new char[from.Length];
  50.             from.CopyTo(0, copy, 0, copy.Length);
  51.             fixed (char* s = str)
  52.             {
  53.                 fixed (char* f = copy)
  54.                 {
  55.                     var l = str.Length;
  56.                     for (int i = 0; i < l; ++i)
  57.                     {
  58.                         var index = Array.IndexOf(copy, s[i]);
  59.                         if (index != -1)
  60.                             f[index] = '\0';
  61.                         else
  62.                             return false;
  63.                     }
  64.                     return true;
  65.                 }
  66.             }
  67.         }
  68.  
  69.     // 105 seconds
  70.         public static bool IsStringMadeOf4(this string str, string from)
  71.         {
  72.             if (from.Except(str).Count() == from.Length - str.Length)
  73.                 return true;
  74.             return false;
  75.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement