Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

in c, 5. Write a function that tests whether two words are anagrams. The functio

ID: 3722433 • Letter: I

Question

in c,

5. Write a function that tests whether two words are anagrams. The function returns 1 if the two words are anagrams, returns 0 otherwise. Two words are anagrams if they are permutations of the same letters. For example, smartest and mattress are anagrams and dumbest and stumble are not anagrams. Assume wordl and word2 are null-terminated strings containing arbitrary lower-case alphabetic letters. Hint: use an array of 26 integers to keep track of how many times each letter is in a word. int are anagrams (char *wordl, char word2)

Explanation / Answer

int are_anagrams( char *word1, char *word2 )

{

    // if the two words are not of the same length

    if( strlen(word1) != strlen(word2) )

        return 0;

   

    // arr1 stores the count of each character in word1

    // arr2 stores the count of each character in word2

    int arr1[26], arr2[26];

   

    int i;

   

    // initialize the elements to 0

    for( i = 0 ; i < 26 ; i++ )

    {

        arr1[i] = 0;

        arr2[i] = 0;

    }

   

    for( i = 0 ; i < strlen(word1) ; i++ )

    {

        // index of a = 0

        // .

        // .

        // .

        // index of z = 25

        int index = (int)word1[i] - 97;

       

        arr1[index]++;

    }

   

    for( i = 0 ; i < strlen(word2) ; i++ )

    {

        // index of a = 0

        // .

        // .

        // .

        // index of z = 25

        int index = (int)word2[i] - 97;

       

        arr2[index]++;

    }

   

    for( i = 0 ; i < 26 ; i++ )

    {

        // if the count of current character are not equal

        if( arr1[i] != arr2[i] )

            return 0;

    }

   

    // if the two words are anagrams

    return 1;

}