Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* header files */
- #include <stdio.h> // get access to printf() and scanf()
- #include <stdbool.h> // get access to boolean values
- #include <string.h> // get access to strlen()
- /* function prototypes */
- bool searchForChar(char c, char* small_word);
- bool isAnagram(char* small_word, char* large_word);
- /* function definitions */
- int main(void)
- {
- char* small_word;
- char* large_word; // set variable for the 2 words
- printf("Small word is: "); // ask for the small one
- scanf("%s", small_word);
- printf("Large word is: "); // ask for the large one
- scanf("%s", large_word);
- char* result;
- if (isAnagram(small_word, large_word)) result = "match!"; // check and print the result
- else result = "no matching!";
- printf("%s\n", result);
- }
- /* for example, we have "cat" and "actor".
- we are going to divide "actor" into triplets like that (act, cto, tor)
- then we will test matching between each triplet and the small word
- if matching present our function will return (true) */
- bool isAnagram(char* small_word, char* large_word)
- {
- int len_of_small = strlen(small_word); // get the length of the small word
- int len_of_large = strlen(large_word); // get the length of the large one
- int counter; // set a counter to check full matching
- for (int i = 0; i <= len_of_large - len_of_small; i++) // iterate over the large word till the index before the end by the length of the small one
- {
- counter = 0; // set the counter at zero
- for (int j = i; j < i + len_of_small; j++) // iterate over the large word from the current index (i) for the length of the small
- {
- if(searchForChar(large_word[j], small_word)) counter++; // check if the current char is present in the small word and if so update counter
- }
- if (counter == len_of_small ) return true; // if counter reach the length of the small word return true
- }
- return false; // else, return false
- }
- bool searchForChar(char c, char* small_word)
- {
- for (int i = 0, len = strlen(small_word); i < len; i++) // iterate over the small word and see if the char sent from prev. function exists in it
- {
- if (small_word[i] == c)
- {
- return true; // if so, return true
- }
- }
- return false; // else, return false
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement