Last active
March 5, 2020 06:44
-
-
Save jakoss/119ff7b18128d88282464859e6943e71 to your computer and use it in GitHub Desktop.
AnagramsBenchmark
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
#LINQPad optimize+ | |
void Main() | |
{ | |
BenchmarkRunner.Run<AnagramsBenchmark>(); | |
} | |
[MemoryDiagnoser] | |
public class AnagramsBenchmark | |
{ | |
[Benchmark] | |
public List<string> AnagramsByOrder() { | |
var word = "abba"; | |
var words = new List<string>(new string[] { "aabb", "abcd", "bbaa", "dada" }); | |
var sortedWord = word.OrderBy(e => e).ToArray(); | |
return words.Where(w => w.OrderBy(c => c).SequenceEqual(sortedWord)).ToList(); | |
} | |
[Benchmark] | |
public List<string> AnagramsByHash() | |
{ | |
var word = "abba"; | |
var words = new List<string>(new string[] { "aabb", "abcd", "bbaa", "dada" }); | |
// Hash of the count of each character in word | |
Dictionary<char, int> wordCount = word.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count()); | |
// Filter words due to the following predicate | |
return words.Where(w => | |
{ | |
// Hash of the count of each character of a word in words | |
Dictionary<char, int> wCount = w.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count()); | |
// Check if the two hashes are equal | |
return wCount.Count == wordCount.Count && !wCount.Except(wordCount).Any(); | |
}).ToList(); | |
} | |
} | |
// Define other methods, classes and namespaces here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment