-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfrequency.c
139 lines (131 loc) · 3.47 KB
/
frequency.c
1
# include "frequency.h"# include <stdio.h># include <stdlib.h># include <string.h>node *new_node(char c) { node *p = (node *) calloc(1, sizeof(node)); if (p!=NULL){ p->letter = c; p->count = 0; p->num_of_ch = 0; p->end = FALSE; } return p;}int read() { int len = 0; int max=0; start = new_node('^'); node *last_n = start; node *curr_n = NULL; char curr_c = fgetc(stdin); while (curr_c != EOF) { if (curr_c >= 'a' && curr_c <= 'z') { //small letters last_n = add_letter(last_n, curr_c, curr_n); len++; } if (curr_c >= 'A' && curr_c <= 'Z') { //big letters curr_c = curr_c + ('a' - 'A'); last_n = add_letter(last_n, curr_c, curr_n); len++; } if (curr_c == '\n' || curr_c == '\t' || curr_c == ' ') { if (len > max) max = len; len = 0; last_n->end = TRUE; last_n->count++; last_n = start; start->count++; // we read a whole word } curr_c = fgetc(stdin); } if (len > max) max = len; last_n->end = TRUE; last_n->count++; return max;}node *add_letter(node *last_n, char curr_c, node *curr_n) { if (last_n->children[curr_c - 'a'] == NULL) { last_n->num_of_ch++; curr_n = new_node(curr_c); if (curr_n==NULL) { free_all(start); exit(1); } last_n->children[curr_c - 'a'] = curr_n; return curr_n; } else { curr_n = last_n->children[curr_c - 'a']; return curr_n; }}void print(node *curr, int i, char *arr) { if (curr->end == TRUE && curr->letter!='^') { arr[i] = curr->letter; arr[i+1] = '\0'; printf("%s %lu\n",arr, curr->count); curr->end = FALSE; } if (curr->letter!='^') { arr[i] = curr->letter; arr[i+1]='\0'; } if ((curr!=start&&curr->num_of_ch!=0)||curr==start){ for (int j = 0; j <=NUM_LETTERS-1; ++j) { if (curr->children[j] != NULL) { i = (int) strlen(arr); print(curr->children[j] ,i, arr); arr[i]='\0'; } } }}void print_reverse(node *curr, int i, char *arr) { if (curr->letter != '^') { arr[i] = curr->letter; arr[i+1] = '\0'; } if ((curr != start && curr->num_of_ch != 0) || curr == start) { for (int j = NUM_LETTERS - 1; j >= 0; --j) { if (curr->children[j] != NULL) { i = (int) strlen(arr); print_reverse(curr->children[j], i, arr); arr[i] = '\0'; } } } i = (int) strlen(arr) - 1; if (curr->end == TRUE && curr->letter != '^') { arr[i] = curr->letter; arr[i + 1] = '\0'; printf("%s %lu\n", arr, curr->count); curr->end = FALSE; }}void free_all(node *curr) { for (int j = 0; j < NUM_LETTERS - 1; ++j) { if (curr->children[j] != NULL) { free_all(curr->children[j]); } } free(curr);}int main(int argc, char **args) { int max =read(); char *arr = (char *) calloc(1,(max+1)* sizeof (char)); if (arr==NULL) { free_all(start); exit(1); } arr[0]='\0'; if(argc==2&&args[1][0]=='r'){ print_reverse(start,0, arr); } else{ print(start,0, arr); } print(start,0, arr); free_all(start); free(arr); exit(0);}