Advertisement
Guest User

bigrams.c

a guest
Jul 3rd, 2015
679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <getopt.h>
  6.  
  7. static int counts[26][26];
  8.  
  9. static inline int
  10. lookup(const char s[static 3])
  11. {
  12.     return counts[s[0] - 'a'][s[1] - 'a'];
  13. }
  14.  
  15. static int
  16. cmp(const void *a, const void *b)
  17. {
  18.     return lookup(b) - lookup(a);
  19. }
  20.  
  21. static void
  22. compute_table(FILE *in)
  23. {
  24.     char last = ' ';
  25.     char c;
  26.     while ((c = fgetc(in)) != EOF) {
  27.         c = tolower(c);
  28.         if (islower(last) && islower(c))
  29.             counts[last - 'a'][c - 'a']++;
  30.         last = c;
  31.     }
  32. }
  33.  
  34. static void
  35. print_listing(FILE *out, int cutoff)
  36. {
  37.     char list[26*26][3];
  38.     for (int i = 0; i < 26 * 26; i++) {
  39.         list[i][0] = i / 26 + 'a';
  40.         list[i][1] = i % 26 + 'a';
  41.         list[i][2] = '\0';
  42.     }
  43.     qsort(list, 26 * 26, sizeof(list[0]), cmp);
  44.     for (int i = 0; i < 26 * 26; i++)
  45.         if (lookup(list[i]) >= cutoff)
  46.             fprintf(out, "%s %d\n", list[i], lookup(list[i]));
  47. }
  48.  
  49. static void
  50. print_table(FILE *out, int cutoff)
  51. {
  52.     fputs("const char table[26][27] = {\n    ", out);
  53.     for (int a = 0; a < 26; a++) {
  54.         fputc('"', out);
  55.         for (int b = 0; b < 26; b++)
  56.             if (counts[a][b] >= cutoff)
  57.                 fputc(b + 'a', out);
  58.         fputc('"', out);
  59.         if (a != 25)
  60.             fputs(", ", out);
  61.     }
  62.     fputs("\n};\n", out);
  63. }
  64.  
  65. int
  66. main(int argc, char **argv)
  67. {
  68.     /* Options */
  69.     enum { LISTING, TABLE } mode = LISTING;
  70.     int cutoff = 1;
  71.  
  72.     /* Option parsing */
  73.     int option;
  74.     while ((option = getopt(argc, argv, "tlc:")) != -1) {
  75.         switch (option) {
  76.             case 't':
  77.                 mode = TABLE;
  78.                 break;
  79.             case 'l':
  80.                 mode = LISTING;
  81.                 break;
  82.             case 'c':
  83.                 cutoff = atoi(optarg);
  84.                 break;
  85.             default:
  86.                 return -1;
  87.         }
  88.     }
  89.  
  90.     compute_table(stdin);
  91.     switch (mode) {
  92.         case LISTING:
  93.             print_listing(stdout, cutoff);
  94.             break;
  95.         case TABLE:
  96.             print_table(stdout, cutoff);
  97.             break;
  98.     }
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement