-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchtrie.c
76 lines (68 loc) · 1.52 KB
/
chtrie.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <stdlib.h>
#include "chtrie.h"
#define ALPHABETSIZE 26
struct chTrie* new_chTrie() {
struct chTrie* new = (struct chTrie*)malloc(sizeof(struct chTrie));
for(int i = 0; i<26; i++) {
new->characters[i] = NULL;
}
new->freq = 0;
new->isEnd = 0;
return new;
}
void add_words_fs(char s[], struct chTrie* root) {
struct chTrie* t = root;
for(int i = 0; s[i] != '\0'; i++) {
if(s[i] != ' ') {
if(t->characters[s[i]-'a'] == NULL) {
t->characters[s[i]-'a'] = new_chTrie();
}
t->freq++;
t = t->characters[s[i]-'a'];
}
else {
t->freq++;
t->isEnd = 1;
t = root;
}
}
t->isEnd = 1;
t->freq++;
}
void print_words(struct chTrie* root, char str[], int level) {
if(root->isEnd == 1) {
str[level] = '\0';
printf("%d %s\n", root->freq, str);
}
struct chTrie* t = root;
for(int i = 0; i<26; i++) {
if(root->characters[i]) {
str[level] = i + 'a';
print_words(root->characters[i], str, level+1);
}
}
}
void print(struct chTrie* root) {
int level = 0;
char str[50];
print_words(root, str, level);
}
int w_search(struct chTrie* t, char str[], int length) {
for(int i = 0; i < length; i++) {
if(t->characters[str[i] - 'a'] == NULL) {
return 0;
}
t = t->characters[str[i] - 'a'];
}
return t->freq;
}
float probability(struct chTrie* t, char stub[], int lenOfStub, char word[], int length) {
float prob;
float freqOfStub = w_search(t, stub, lenOfStub);
float freqOfWord = w_search(t, word, length);
if(freqOfStub) {
prob = freqOfWord/freqOfStub;
}
return prob;
}