Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <stdbool.h>
- #include "exercise1_benoit_dardenne.h"
- void anagrams(char* dictionary[], int nwords)
- {
- StringCouple* table = sortStrings(dictionary, nwords);
- if(table == NULL)
- {
- fprintf(stderr, "Memory allocation failure.\n");
- return;
- }
- qsort(table, nwords, sizeof(StringCouple), compareStrings);
- findAnagrams(table, nwords);
- free(table);
- }
- StringCouple* sortStrings(char* strings[], size_t count)
- {
- StringCouple* table = malloc(count * sizeof(StringCouple));
- if(table == NULL) return NULL;
- char* words = malloc(count * STRING_MAX);
- if(words == NULL)
- {
- free(table);
- return NULL;
- }
- size_t i;
- for(i = 0; i < count; i++)
- {
- table[i].source = strings[i];
- table[i].sorted = words;
- char* tmp = words;
- words = stpcpy(words, strings[i]);
- //Sort the letters
- qsort(tmp, words - tmp, 1, compareChars);
- words++;
- }
- return table;
- }
- int compareChars(const void* elemA, const void* elemB)
- {
- return *(char *) elemA - * (char *) elemB;
- }
- int compareStrings(const void* elemA, const void* elemB)
- {
- return strncmp( ((StringCouple *) elemA)->sorted, ((StringCouple *) elemB)->sorted, STRING_MAX);
- }
- void findAnagrams(StringCouple table[], size_t count)
- {
- bool inGroup = false;
- size_t i;
- for(i = 1; i < count; i++)
- {
- if(strncasecmp(table[i].sorted, table[i - 1].sorted, STRING_MAX) == 0)
- {
- if(!inGroup)
- {
- printf("%s\n", table[i - 1].source);
- inGroup = true;
- }
- printf("%s\n", table[i].source);
- }
- else
- {
- if(inGroup)
- printf("\n");
- inGroup = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement