Advertisement
Guest User

Untitled

a guest
Feb 25th, 2012
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. #include <stdbool.h>
  6.  
  7. #include "exercise1_benoit_dardenne.h"
  8.  
  9. void anagrams(char* dictionary[], int nwords)
  10. {
  11.     StringCouple* table = sortStrings(dictionary, nwords);
  12.  
  13.     if(table == NULL)
  14.     {
  15.         fprintf(stderr, "Memory allocation failure.\n");
  16.         return;
  17.     }
  18.  
  19.     qsort(table, nwords, sizeof(StringCouple), compareStrings);
  20.     findAnagrams(table, nwords);
  21.     free(table);
  22. }
  23.  
  24. StringCouple* sortStrings(char* strings[], size_t count)
  25. {
  26.     StringCouple* table = malloc(count * sizeof(StringCouple));
  27.     if(table == NULL) return NULL;
  28.  
  29.     char* words = malloc(count * STRING_MAX);
  30.     if(words == NULL)
  31.     {
  32.         free(table);
  33.         return NULL;
  34.     }
  35.  
  36.     size_t i;
  37.     for(i = 0; i < count; i++)
  38.     {
  39.         table[i].source = strings[i];
  40.         table[i].sorted = words;
  41.  
  42.         char* tmp = words;
  43.  
  44.         words = stpcpy(words, strings[i]);
  45.  
  46.         //Sort the letters
  47.         qsort(tmp, words - tmp, 1, compareChars);
  48.         words++;
  49.     }
  50.  
  51.     return table;
  52. }
  53.  
  54. int compareChars(const void* elemA, const void* elemB)
  55. {
  56.     return *(char *) elemA - * (char *) elemB;
  57. }
  58.  
  59. int compareStrings(const void* elemA, const void* elemB)
  60. {
  61.     return strncmp( ((StringCouple *) elemA)->sorted, ((StringCouple *) elemB)->sorted, STRING_MAX);
  62. }
  63.  
  64. void findAnagrams(StringCouple table[], size_t count)
  65. {
  66.     bool inGroup = false;
  67.     size_t i;
  68.     for(i = 1; i < count; i++)
  69.     {
  70.         if(strncasecmp(table[i].sorted, table[i - 1].sorted, STRING_MAX) == 0)
  71.         {
  72.             if(!inGroup)
  73.             {
  74.                 printf("%s\n", table[i - 1].source);
  75.                 inGroup = true;
  76.             }
  77.             printf("%s\n", table[i].source);
  78.         }
  79.         else
  80.         {
  81.             if(inGroup)
  82.                 printf("\n");
  83.  
  84.             inGroup = false;
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement