I'm attempting to count the number of trigrams, or three letter sequences, in a block of text. I have some code already that successfully counts the number of bigrams (2 letter sequence) using a 2d array, but I'm having some trouble altering it to accept trigrams.
#include <stdio.h>
int main(void) {
int count['z' - 'a' + 1]['z' - 'a' + 1] = {{ 0 }};
int c0 = EOF, c1;
FILE *plain = fopen("filename.txt", "r");
if (plain != NULL) {
while ((c1 = getc(plain)) != EOF) {
if (c1 >= 'a' && c1 <= 'z' && c0 >= 'a' && c0 <= 'z') {
count[c0 - 'a'][c1 - 'a']++;
}
c0 = c1;
}
fclose(plain);
for (c0 = 'a'; c0 <= 'z'; c0++) {
for (c1 = 'a'; c1 <= 'z'; c1++) {
int n = count[c0 - 'a'][c1 - 'a'];
if (n) {
printf("%c%c: %d\n", c0, c1, n);
}
}
}
}
return 0;
}
Edit: Here's the code I've already tried. I was hoping to just expand the 2d array to a 3d array, but this returns nothing.
#include <stdio.h>
int main(void) {
int count['z' - 'a' + 1]['z' - 'a' + 1]['z' - 'a' + 1] = {{{ 0 }}};
int c0 = EOF, c1, c2;
FILE *plain = fopen("filename.txt", "r");
if (plain != NULL) {
while ((c1 = getc(plain)) != EOF) {
if (c1 >= 'a' && c1 <= 'z' && c0 >= 'a' && c0 <= 'z' && c2 >= 'a' && c2 <= 'z') {
count[c0 - 'a'][c1 - 'a'][c2 - 'a']++;
}
c0 = c1;
c1 = c2;
}
fclose(plain);
for (c0 = 'a'; c0 <= 'z'; c0++) {
for (c1 = 'a'; c1 <= 'z'; c1++) {
for (c2 = 'a'; c2 <= 'z'; c2++) {
int n = count[c0 - 'a'][c1 - 'a'][c2 - 'a'];
if (n) {
printf("%c%c%c: %d\n", c0, c1, c2, n);
}
}
}
}
}
return 0;
}
For example, this code prints all occurances of bigrams such as aa, ab, ac, etc. But I need it to count the occurances of aaa, aab, ... zzz. Any help would be greatly appreciated!
Edit 2: now it successfully prints the correct output, but it needs to be in descending order (most used trigram at the top)