Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created October 3, 2016 19:47
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 guitarrapc/eb10298d35b26a7b0ad36acace1795cb to your computer and use it in GitHub Desktop.
Save guitarrapc/eb10298d35b26a7b0ad36acace1795cb to your computer and use it in GitHub Desktop.
void Main()
{
Func<string, string, bool> anagram = (first, second) =>
{
if (first == null || second == null) return false;
if (first.Length != second.Length) return false;
var dic = new Dictionary<char, int>();
foreach (var item in first)
{
int i;
if (dic.TryGetValue(item, out i))
{
dic[item] = i + 1;
}
else
{
dic[item] = 1;
}
}
//var dic = first.GroupBy(c => c).ToDictionary(kv => kv.Key, kv => kv.Count());
foreach (var item in second)
{
int i;
if (!dic.TryGetValue(item, out i))
{
return false;
}
i--;
if (i == 0)
{
dic.Remove(item);
}
else
{
dic[item] = i;
}
}
return true;
};
var sw = Stopwatch.StartNew();
foreach (var item in Enumerable.Range(0, 100000))
{
anagram(" ", " ");
anagram("1", "1");
anagram("eros", "rose");
anagram("eros", "lose");
anagram("", "rose");
anagram("eros", "rosesssss");
anagram("bab", "aba");
anagram(" ", " ");
anagram(null, null);
anagram(null, "");
anagram("hoge", null);
anagram("1", "2");
}
sw.Stop();
$"{sw.Elapsed.TotalMilliseconds}ms".Dump("Dictionary");
Debug.Assert(anagram("", "").Dump());
Debug.Assert(anagram(" ", " ").Dump());
Debug.Assert(anagram("1", "1").Dump());
Debug.Assert(anagram("eros", "rose").Dump());
Debug.Assert(anagram("eros", "lose").Dump() == false);
Debug.Assert(anagram("", "rose").Dump() == false);
Debug.Assert(anagram("eros", "rosesssss").Dump() == false);
Debug.Assert(anagram("bab", "aba").Dump() == false);
Debug.Assert(anagram(" ", " ").Dump() == false);
Debug.Assert(anagram(null, null).Dump() == false);
Debug.Assert(anagram(null, "").Dump() == false);
Debug.Assert(anagram("hoge", null).Dump() == false);
Debug.Assert(anagram("1", "2").Dump() == false);
Debug.Assert(anagram("abcde", "abcd").Dump() == false);
}
@guitarrapc
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment