Reputation: 3
I'm a beginner in C#. I need some help. Here's the code I made:
static void anagrame_dict(String [] s)
{
ArrayList x = new ArrayList();
foreach (string cuv in s)
{
Dictionary<char, int> dict = new Dictionary<char, int>();
foreach (char lit in cuv)
{
if (dict.ContainsKey(lit))
{
dict[lit] += 1;
}
else
{
dict[lit] = 1;
}
}
x.Add(dict);
}
..............
I made an arraylist of dictionaries but now I don't know how to access the keys and values in every dictionary from the arraylist to compare them and see which words are anagrams.
This is a sample
input String[]b={ "casa", "djf", "ajkd", "saca", "asca", "lama", "ajs", "mala", "kasa", "saka", "idm", "kaj", "hfk" };
By anagrams I mean words with same characters but different order like "casa" and "saca".
Upvotes: 0
Views: 630
Reputation: 39132
Given two strings, they are anagrams of each other if you SORT their characters and the resulting sorted sequences are the same.
Here's a lambda that receives a string and returns its characters in sorted order:
Func<String, String> sorted = w => new String(w.ToCharArray().OrderBy(c => c).ToArray());
Example usage:
String word = "alphabet";
Console.WriteLine(word + " ==> " + sorted(word));
Output:
alphabet ==> aabehlpt
Now we can iterate over each word in your input array and get the sorted "signature" of it. As we iterate, we'll ask the array to find all other words in the array that are not the current word, but do have a matching "signature".
We can use a Dictionary<String, List<String>>
to associate each source word with a list of any anagrams found.
Here's the whole thing put together:
String[] words ={ "casa", "djf", "ajkd", "saca", "asca", "lama", "ajs", "mala", "kasa", "saka", "idm", "kaj", "hfk" };
Func<String, String> sorted = w => new String(w.ToCharArray().OrderBy(c => c).ToArray());
Dictionary<String, List<String>> anagrams = new Dictionary<string, List<string>>();
foreach (String word in words)
{
var matches = words.Where(w => w != word && sorted(w) == sorted(word)).ToList();
anagrams.Add(word, matches);
}
foreach (var result in anagrams)
{
Console.WriteLine(result.Key + " ==> " + String.Join(", ", result.Value));
}
Output:
casa ==> saca, asca
djf ==>
ajkd ==>
saca ==> casa, asca
asca ==> casa, saca
lama ==> mala
ajs ==>
mala ==> lama
kasa ==> saka
saka ==> kasa
idm ==>
kaj ==>
hfk ==>
Upvotes: 1