Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include <string.h>
- #include <getopt.h>
- static int counts[26][26];
- static inline int
- lookup(const char s[static 3])
- {
- return counts[s[0] - 'a'][s[1] - 'a'];
- }
- static int
- cmp(const void *a, const void *b)
- {
- return lookup(b) - lookup(a);
- }
- static void
- compute_table(FILE *in)
- {
- char last = ' ';
- char c;
- while ((c = fgetc(in)) != EOF) {
- c = tolower(c);
- if (islower(last) && islower(c))
- counts[last - 'a'][c - 'a']++;
- last = c;
- }
- }
- static void
- print_listing(FILE *out, int cutoff)
- {
- char list[26*26][3];
- for (int i = 0; i < 26 * 26; i++) {
- list[i][0] = i / 26 + 'a';
- list[i][1] = i % 26 + 'a';
- list[i][2] = '\0';
- }
- qsort(list, 26 * 26, sizeof(list[0]), cmp);
- for (int i = 0; i < 26 * 26; i++)
- if (lookup(list[i]) >= cutoff)
- fprintf(out, "%s %d\n", list[i], lookup(list[i]));
- }
- static void
- print_table(FILE *out, int cutoff)
- {
- fputs("const char table[26][27] = {\n ", out);
- for (int a = 0; a < 26; a++) {
- fputc('"', out);
- for (int b = 0; b < 26; b++)
- if (counts[a][b] >= cutoff)
- fputc(b + 'a', out);
- fputc('"', out);
- if (a != 25)
- fputs(", ", out);
- }
- fputs("\n};\n", out);
- }
- int
- main(int argc, char **argv)
- {
- /* Options */
- enum { LISTING, TABLE } mode = LISTING;
- int cutoff = 1;
- /* Option parsing */
- int option;
- while ((option = getopt(argc, argv, "tlc:")) != -1) {
- switch (option) {
- case 't':
- mode = TABLE;
- break;
- case 'l':
- mode = LISTING;
- break;
- case 'c':
- cutoff = atoi(optarg);
- break;
- default:
- return -1;
- }
- }
- compute_table(stdin);
- switch (mode) {
- case LISTING:
- print_listing(stdout, cutoff);
- break;
- case TABLE:
- print_table(stdout, cutoff);
- break;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement