anagram_finder.cs in C#
Group words by their sorted letters and the anagrams find themselves.
// anagram_finder: group a word list by sorted letters, print the families
var words = new[]
{
"listen", "silent", "enlist", "google", "banana",
"stressed", "desserts", "elbow", "below", "state", "taste",
};
var families = words
.GroupBy(w => string.Concat(w.OrderBy(c => c)))
.Where(g => g.Count() > 1)
.OrderByDescending(g => g.Count())
.ThenBy(g => g.Key)
.ToList();
Console.WriteLine($"{words.Length} words in");
foreach (var family in families)
{
Console.WriteLine($" {string.Join(" = ", family)}");
}
var covered = families.Sum(f => f.Count());
Console.WriteLine($"{covered} words share their letters with another");
How it works
string.Concat(w.OrderBy(c => c))is the canonical-form key.- Groups larger than one are anagram families.
- Ordering by size, then key, makes the output stable.
Keywords and builtins used here
foreachinnewstringvar
The run, in numbers
- Lines
- 22
- Characters to type
- 626
- Tokens
- 141
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 94 seconds.
Step 2 of 2 in Encore, step 17 of 17 in LINQ in depth.