Program to find anagram words from given dictionary using prime numbers
Here is the code :
Thanks
Another Method to do the same without using prime number.
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
void main()
{
int prime[26] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 };
string dictionary[] = { "duplicate", "licdupate", "duplteica", "catedupli", "plicduate", "patelicdu", "duplicata", "duplacate" };
char *search = "duplicate";
const int kElem = 8;
int len = strlen(search);
long long search_product = 1;
for (int index = 0; index < len; ++index)
{
search_product *= prime[search[index] - 'a'];
}
for (int index = 0; index < kElem; ++index)
{
const char *text = dictionary[index].c_str();
int textLen = strlen(text);
long long result = 1;
for (int charIndex = 0; charIndex < textLen; ++charIndex)
{
result *= prime[text[charIndex] - 'a'];
}
if (result == search_product) {
cout << index + 1 << ". '" << text << "' is anagram to " << search << endl;
}
else {
cout << index + 1 << ". '" << text << "' is not anagram to " << search << endl;
}
}
_getch();
}
Thanks
Another Method to do the same without using prime number.

Comments
Post a Comment