C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Input string/alphabetized form:
cat act
tca act
senators aeonrsst
treasons aeonrsst
Main: We read in the word list. The word list used here is a version of the ENABLE word list available online.
Next: For each line, it alphabetizes the letters. This forms the alphabetized key for that word.
Alphabetize StringDictionary: We look up the key in the Dictionary. If the alphabetized key is found, we append the current word.
DictionaryAnd: In this way, we hash all real words at keys of their alphabetized forms. We can instantly retrieve the real words.
C# program that finds anagrams in file
using System;
using System.Collections.Generic;
using System.IO;
class Anagrams
{
static void Main()
{
// Read and sort dictionary.
var d = Read();
// Read in user input and show anagrams.
string line;
while ((line = Console.ReadLine()) != null)
{
Show(d, line);
}
}
static Dictionary<string, string> Read()
{
var d = new Dictionary<string, string>();
// Read each line.
using (StreamReader r = new StreamReader("enable1.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
// Alphabetize the line for the key.
// ... Then add to the value string.
string a = Alphabetize(line);
string v;
if (d.TryGetValue(a, out v))
{
d[a] = v + "," + line;
}
else
{
d.Add(a, line);
}
}
}
return d;
}
static string Alphabetize(string s)
{
// Convert to char array, then sort and return.
char[] a = s.ToCharArray();
Array.Sort(a);
return new string(a);
}
static void Show(Dictionary<string, string> d, string w)
{
// Write value for alphabetized word.
string v;
if (d.TryGetValue(Alphabetize(w), out v))
{
Console.WriteLine(v);
}
else
{
Console.WriteLine("-");
}
}
}
Output
martian,tamarin
opts,post,pots,spot,stop,tops
assentor,senators,starnose,treasons
Also: For better performance, you can persist the alphabetized key-value pairs to the disk. Using a binary file would also help.
Convert Dictionary, StringAlso: You can use Levenshtein distance to find similar strings. But it is not helpful in Scrabble.
Levenshtein