Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- anagram_v1.c
- Anagram is a word or phrase formed by
- rearranging letters of different word or phrase.
- For example
- "BRUSH" and "SHRUB",
- "TALE" and "LATE"
- are anagrams of each other.
- How to examine if it is an anagram?
- If all the characters of one sting are in another string, it is an anagram.
- An elegant solution proposed by Steven Serrano
- https://web.facebook.com/stvnsrrn18
- is just to get the sum of characters in both words and equal it,
- for every character in the ascii there's a decimal equivalent.
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // returns 1 if word1 and word2 are anagrams, otherwise returns 0.
- // version without pointers
- int are_anagrams( char word1[], char word2[] )
- {
- int i=0, sum1=0, sum2=0;
- while( word1[i] != '\0' ) // from the first to the last character of word1
- {
- sum1 = sum1 + (int)word1[i];
- i++; // increment counter
- }
- i = 0; // reset counter
- while( word2[i] != '\0' ) // from the first to the last character of word2
- {
- sum2 = sum2 + (int)word2[i];
- i++; // increment counter
- }
- if( sum1 == sum2 ) // if both sums are the same
- return 1;
- else
- return 0;
- }
- // returns 1 if word1 and word2 are anagrams, otherwise returns 0.
- // version with pointers
- int are_anagrams_v1( char *word1, char *word2 )
- {
- int i=0, sum1=0, sum2=0;
- while( *(word1+i) != '\0' ) // from the first to the last character of word1
- {
- sum1 = sum1 + (int)*(word1+i);
- i++; // increment counter
- }
- i = 0; // reset counter
- while( *(word2+i) != '\0' ) // from the first to the last character of word2
- {
- sum2 = sum2 + (int)*(word2+i);
- i++; // increment counter
- }
- if( sum1 == sum2 ) // if both sums are the same
- return 1;
- else
- return 0;
- }
- int main(void)
- {
- char word1[] = "brush";
- char word2[] = "shrub";
- if( are_anagrams(word1, word2) )
- printf("\n %s and %s are anagrams. \n", word1, word2 );
- else
- printf("\n %s and %s are not anagrams. \n", word1, word2 );
- if( are_anagrams_v1(word1, word2) )
- printf("\n %s and %s are anagrams. \n", word1, word2 );
- else
- printf("\n %s and %s are not anagrams. \n", word1, word2 );
- return 0;
- } // main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement