Hi albert,
I think you are going to like this solution for you. Based on your code I set up a simultaneous test on both strings to determine if they are anagram. Thus we cut down your loop by magnitudes enhancing performance and accuracy. Check it out...
CODE
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char phrase1[500], phrase2[500];
cout << "Enter the first string" << endl;
cin.getline (phrase1, 500);
cout << "Enter the second string" << endl;
cin.getline (phrase2, 500);
char LowAlphList[] = {"abcdefghijklmnopqrstuvwxyz"};
char UpAlphList[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
// Set our arrays to zero all the way through
int alphCount1[26] = {0};
int alphCount2[26] = {0};
// Get the length of each phrase
int count = (int)strlen(phrase1);
int count2 = (int)strlen(phrase2);
// If they are not identical length, we automatically know they are not anagrams.
if (count == count2) {
// Loop through the letters of each phrase (which are identical)
for (int i = 0; i < count; i++) {
// Loop through the alphabet for both phrases simulatneously
// Increment their respective spots in their own array
// They are in sync, like it?;)
for (int j = 0; j < 26; j++) {
if ((phrase1[i] == LowAlphList[j]) || (phrase1[i] == UpAlphList[j])) {
alphCount1[j] += 1;
}
if ((phrase2[i] == LowAlphList[j]) || (phrase2[i] == UpAlphList[j])) {
alphCount2[j] += 1;
}
}
}
bool identical = true;
// Last, compare the two arrays to see if they have the same counts.
for (int i = 0; i < 26; i++) {
if (alphCount1[i] != alphCount2[i]) {
identical = false;
}
}
// If the arrays have the same count, identical flag would not be set to false.
if (identical) { cout << "They are anagrams" << endl; }
else { cout << "They are not anagrams" << endl; }
}
else { cout << "They are not anagrams" << endl; }
system("PAUSE");
return 0;
}
You can read through the in code comments to see what I am doing. However, it is pretty simplistic in nature. Once we determine they are the same size, we can test both strings using the same looping mechanism. We then just compare the results at the end.
Give it a whirl and enjoy!
"At DIC we be dual wielding, string checking, anagram testing code ninjas!"
This post has been edited by Martyr2: 21 Nov, 2007 - 05:01 PM