/* Name: ex8-16.c Purpose: anagram tester Author: Bill Slough */ #include #include #include #define N 15 /* maximum length of each input word */ #define ALPHSIZE 26 /* number of letters in the alphabet */ int getline(char a[ ], int size, bool *overflow); void changeCase(char a[ ], int n); bool allZeros(int x[ ], int n); int main() { char firstWord[N]; /* arrays for each of the words */ char secondWord[N]; int firstLength; /* length of each word */ int secondLength; bool overflow; /* buffer over-run? */ int freq[ALPHSIZE] = {0}; /* all 0's initially */ int i; char ch; /* Get the first word */ printf("Enter first word: "); firstLength = getline(firstWord, N, &overflow); /* Terminate execution if there were too many input characters */ if (overflow) { printf("Error in input: buffer overflow.\n"); return 1; } /* Get the second word */ printf("Enter second word: "); secondLength = getline(secondWord, N, &overflow); /* Terminate execution if there were too many input characters */ if (overflow) { printf("Error in input: buffer overflow.\n"); return 1; } if (firstLength != secondLength) printf("The words are not anagrams -- mismatched lengths.\n"); /* ensure both words are of the same case */ changeCase(firstWord, firstLength); changeCase(secondWord, secondLength); /* determine letter frequency in the first word */ for (i = 0; i < firstLength; i++) { ch = firstWord[i]; if (isalpha(ch)) freq[ch - 'a']++; /* boost count for this letter */ } /* do the same for the second word, this time decreasing counts */ for (i = 0; i < secondLength; i++) { ch = secondWord[i]; if (isalpha(ch)) freq[ch - 'a']--; } if (allZeros(freq, ALPHSIZE)) printf("The words are anagrams.\n"); else printf("The words are not anagrams.\n"); return 0; } /* Read a line of characters into the array a, which has capacity = size */ int getline(char a[ ], int size, bool *overflow) { int i; char ch; i = 0; while (i < size && (ch = getchar()) != '\n') { a[i++] = ch; } *overflow = (i == size) && (getchar() != '\n'); return i; } /* Replace the letters in a word with its lower-case counterparts */ void changeCase(char a[ ], int n) { int i; for (i = 0; i < n; i++) { a[i] = tolower(a[i]); } } /* is every element of a given array zero? */ bool allZeros(int x[ ], int n) { int i; for (i = 0; i < n; i++) if (x[i] != 0) return false; return true; }