Hello
I have made a function that determines whether 2 words are an anagram or not.
My Problem is: that if the word contains 2 or more of the same letters(eg hello, arrest, gall) the function doesn't work even when the 2 words input are an anagram,
If i input "ate" & "eat" my function returns true - so it works
But if I input "mello" & "ollem" - I know these are not words but it should still return true, but it doesn't because the repeated 'l' confuses the function...I think? :P
function:
bool areAnagrams (string s1, string s2)
// pre : s1 and s2 are lower case strings
// post : returns true if s1 and s1 are anagrams
// and otherwise false
{
int count = 0;
if (s1.length() != s2.length()) {
return false;
}
// check if all the letters that occur in s1 are
// present in s2 also.
for (int i=0; i<(int)s1.length(); i++) {
for (int j=0; j<(int)s1.length(); j++) {
if (s1[i]==s2[j]) count++;
}
}
if (count==(int)s1.length())
{
return true;
}
else return false;
}
Whole code:
#include <iostream>
using namespace std;
bool areAnagrams(string s1, string s2);
int main()
{
string word1, word2;
cout << "Enter pairs of words - terminate with control-z" << endl;
while (cin >> word1 >> word2) // complete this
{
if (areAnagrams (word1, word2))
cout << word1 << " and " << word2 << " are anagrams " << endl;
else
cout << word1 << " and " << word2 << " are not anagrams " << endl;
}
system("pause");
return 0;
}
bool areAnagrams (string s1, string s2)
// pre : s1 and s2 are lower case strings
// post : returns true if s1 and s1 are anagrams
// and otherwise false
{
int count = 0;
if (s1.length() != s2.length()) {
return false;
}
// check if all the letters that occur in s1 are
// present in s2 also.
for (int i=0; i<(int)s1.length(); i++) {
for (int j=0; j<(int)s1.length(); j++) {
if (s1[i]==s2[j]) count++;
}
}
if (count==(int)s1.length())
{
return true;
}
else return false;
}