This is the exercise that I have to deal with:
You are given a word and a list of words. Your task is to check whether all the words from the list are anagrams of the word. Input Read from the standard input
On the first line, find W - the word to check against; On the second line, find N - the number of words in the list of words WORDS; On the next N lines, the words from WORDS; Output Print to the standard output
For each word from WORDS print either: "Yes", if the word is an anagram of W; "No", if the word is NOT an anagram of W;
And this is my code:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string word1 = Console.ReadLine();
char[] mainWord = word1.ToLower().ToCharArray();
Array.Sort(mainWord);
int numberOfWords = int.Parse(Console.ReadLine());
List<Array> anagramWords = new List<Array>();
for (int i = 0; i < numberOfWords; i )
{
string wordForList = Console.ReadLine();
char[] wordCharacters = wordForList.ToLower().ToCharArray();
Array.Sort(wordCharacters);
anagramWords.Add(wordCharacters);
}
foreach(object word in anagramWords)
{
if (word == mainWord)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
For some reason, the answer that I get is always No.
CodePudding user response:
if (word == mainWord)
doesn't compare the content of the word array with the content of the other array.
Array variables are references types, or, in other words. they just contain the reference to the memory area where the elements of the array are stored.
So if you compare the arrays in that way you are comparing
two values (two references) that point to the memory area where the respective elements are stored. Of course these values are different because, even if they contains the same characters, the elements are stored in different memory areas.
To solve your problem a different approach is needed. Something like this should work
static void Main()
{
string word1 = Console.ReadLine();
IEnumerable<char>mainWord = word1.ToLower().OrderBy(w => w);
int numberOfWords = int.Parse(Console.ReadLine());
List<IEnumerable<char>> anagramWords = new List<IEnumerable<char>>();
for (int i = 0; i < numberOfWords; i )
{
string wordForList = Console.ReadLine();
IEnumerable<char> wordCharacters = wordForList.ToLower().OrderBy(fl => fl);
anagramWords.Add(wordCharacters);
}
foreach (var word in anagramWords)
{
// Here we are asking to compare the full set of elements
// with each other and we find if they contain the same data.
if (word.SequenceEqual(mainWord))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}