-1

I was implementing a code that prints all the anagrams together. Now I am stuck and I don't know how to move forward.

What I want to do is :

Given an array str[]={"cat","dog","tac",god"}

I create an array dup[] same as str[].

Now I sort the duplicate array which now becomes {"act ","dgo","act","dgo"}

Here I find the indexes of same elements i.e. 0 and 2 && 1 and 3

In original array I print the index 0 and 2 together and 1 and 3 together ,

Now I don't know how to sort the string without changing the indices .

oz123
  • 27,559
  • 27
  • 125
  • 187
user2456752
  • 85
  • 1
  • 4
  • 12
  • If I got it correctly, for the given array str[], you would like to print all anagrams? cat-tac dog-god – Maggie Sep 18 '13 at 06:04
  • Maybe that's my poor language skills, but I can't tell what's your problem. – zubergu Sep 18 '13 at 06:09
  • http://stackoverflow.com/questions/18781106/generate-same-unique-hash-code-for-all-anagrams/ and http://stackoverflow.com/questions/18834128/c-finding-anagrams-in-words – Leeor Sep 18 '13 at 06:15

2 Answers2

1

The easiest approach here would be to calculate hash of each word and store it in the auxiliary array. After that, traverse the auxiliary array and display items with the same values. Eg.

int i=0;
char hash[i][256];
for (i=0; i<n; i++) {
   hash[i] = calculate_hash(str[i]);
}
int j=0;
for (i=0;i<n; i++) {
   for (j=i+1; j<n; j++) {
     if (strcmp(hash[i], hash[j] == 0) {
        printf ("%s %s", str[i], str[j]);
    }
   }
}

My C is a bit rusty, but I think it covers up the idea.

Maggie
  • 7,823
  • 7
  • 45
  • 66
0

You are halfway there: after sorting the characters inside the character strings, you sort this list again "the regular way" -- alphabetically. Then all anagrams appear in order: "act","act","dgo","dgo". However, with this sort you loose the connection with your original array.

Instead of storing your words into a single char array, create a simple structure. In this you also add the original index, so after sorting you can retrieve them.

Jongware
  • 22,200
  • 8
  • 54
  • 100