Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.
My idea is to sort individual words firstly. And then sort the array of words. In this way, the anagrams will be together. The following is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct word_with_ind
{
char* word;
int ind;
}*word_with_ind_ptr;
int comp_char(const void* x, const void* y)
{
char* c1 = (char*)x;
char* c2 = (char*)y;
return *c1 - *c2;
}
int comp_str(const void* x, const void* y)
{
const word_with_ind_ptr w1 = (word_with_ind_ptr)x;
const word_with_ind_ptr w2 = (word_with_ind_ptr)y;
return strcmp(w1->word, w2->word);
}
void destroy(word_with_ind_ptr x, int size)
{
for(int i = 0; i < size; ++i)
{
free(x[i].word);
}
free(x);
}
void print_anagrams_together(char* word[], int size)
{
//make a copy of the original word array. And sort
//the individual words
word_with_ind_ptr x = (word_with_ind_ptr)malloc(sizeof(struct word_with_ind)*size);
for(int i = 0; i < size; ++i)
{
x[i].ind = i;
x[i].word = (char*)malloc(sizeof(char)*(strlen(word[i])+1));
strcpy(x[i].word, word[i]);
qsort(x[i].word, strlen(x[i].word), sizeof(char), comp_char);
}
//sort the array of words
qsort(x, size, sizeof(struct word_with_ind), comp_str);
//print result
for(int i = 0; i < size; ++i)
{
printf("%s\n", word[x[i].ind]);
}
//free memory
destroy(x, size);
}
int main()
{
char* word[] = {"cat", "dog", "tac", "god", "act"};
int size = sizeof(word)/sizeof(word[0]);
print_anagrams_together(word, size);
getchar();
return 0;
}