Program to find anagram with in a given dictionary - C++

Here is the code :

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

void main()
{
  string dictionary[] = { "duplicate", "licdupate", "duplteica", "catedupli", "plicduate", "patelicdu", "duplicata", "duplacate" };
  char *search = "duplicate";
  const int kElem = 8;
  int len = strlen(search);

  for (int index = 0; index < kElem; ++index)
  {
    const char *text = dictionary[index].c_str();

    int textLen = strlen(text);
    int result = 0;

    if (textLen == len)
    {
      for (int charIndex = 0; charIndex < len; ++charIndex)
      {
        result ^= (search[charIndex] ^ text[charIndex]);
      }
    }
    else {
      result = -1;
    }

    if (result == 0) {
      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 using prime number.

Comments

Popular Posts