Skip to content

Instantly share code, notes, and snippets.

@jakoss
Last active March 5, 2020 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakoss/119ff7b18128d88282464859e6943e71 to your computer and use it in GitHub Desktop.
Save jakoss/119ff7b18128d88282464859e6943e71 to your computer and use it in GitHub Desktop.
AnagramsBenchmark
#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