Anagram problem

Sep 9, 2015 at 6:11pm
Hello. I have to find out whether a word is made up of the same letters with another word. For example: "car" and "arc" are good because they are made up of the letters 'a','c','r' while the words "bang" and "wang" are not good because 'w' is not int the word "bang".

#include<iostream>
#include<cstring>
using namespace std;
string a,b;
int main(){

int n,m;
getline(cin,a);
getline(cin,b);
m=a.length();
n=b.length();
int i=-1,j;
int found;

do
{

i++;
found=0;
for(j=0;j<n;j++)
if(a[i]==b[j])
found=1;


}
while(found==0 || i==m);

if(found) cout<<"YES";
else cout<<"NO";
return 0;
}

The computer always yields "Yes".
Last edited on Sep 9, 2015 at 6:12pm
Sep 9, 2015 at 9:36pm
Please use [code] tags -- it is very difficult to read your code like that.

The main problem with your algorithm is with the condition in your do..while loop.

What you are trying to do is check to see if every letter found in one is the same as the letter found in another.

So if the first letter in a[] is anywhere in b[], then 'found' will be true. If a[] and b[] really are anagrams, then 'found' should always be true. It is when it is not true that you have learned something.

Also, i==m is only true at the end of the loop. I think you'd rather continue while i!=m, right?

One other consideration. What happens if m!=n?

Hope this helps.
Sep 10, 2015 at 8:56am
Thank you ! It works fine ! If m!=n they cannot be anagrams.
Sep 10, 2015 at 12:30pm
Good. Did you make sure to add code to check whether m!=n?
Sep 10, 2015 at 1:21pm
Hmm...

Have you tried testing the words aabc and abbc. They should not be anagrams.

Think about rearanging the letters in both words so that the letters are sorted alphabetically. For example, the word 'start' would turn into 'arstt'.
Topic archived. No new replies allowed.