-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrieCode.cpp
152 lines (125 loc) · 2.45 KB
/
TrieCode.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include "TrieCode.h"
Node::Node()
{
NodeStr= "";
info = '\0';
flag = false;
for(int i = 0 ; i < 256; i++)
{
ptrs[i] = NULL;
}
}
Node::~Node()
{
cout<<"destructor";
}
void Node::insert(string localStr, int posistion , class Node *root)
{
cout<<"-->"<<posistion<<endl;
// base case for stopping recurssion
if(localStr.length() == posistion)
{
root->NodeStr= localStr;
cout<<"note here-->"<<posistion<<endl;
return;
}
// insert the string if empty
if( root->ptrs[word[posistion]] == NULL )
{
cout<<"\ncreating new branch";
Node *currentnode = new Node;
currentnode->info = localStr[posistion];
cout<<"\nword[pos] -->"<<word[posistion];
root->ptrs[localStr[posistion]] = currentnode;
insert(localStr,posistion+1,root->ptrs[localStr[posistion]]);
}
else // increment posistion by +1
{
cout<<"\nNot Empty";
insert(localStr,posistion+1,root->ptrs[localStr[posistion]]);
}
}
void Node::suggest(string localStr, int posistion , class Node *root)
{
if( (localStr != root->NodeStr) && (root->ptrs[localStr[posistion]] != NULL ) )
{
suggest(localStr,posistion+1,root->ptrs[localStr[posistion]]);
}
else
{
printfunc(root);
}
}
void Node::findword(string localStr, int posistion , class Node *root)
{
if( (root->NodeStr!= localStr) && (root->ptrs[localStr[posistion]] != NULL) )
{
findword(localStr,posistion+1,root->ptrs[localStr[posistion]]);
}
else
{
if( localStr == root->NodeStr)
{
cout<<endl<<localStr<<" and "<<root->NodeStr<<" Correct"<<endl;
}
else
{
cout<<"\n\nWord not found!";
}
}
}
void Node::printfunc(class Node *root)
{
//cout<<"\nprintfunc";
for(int i = 0; i < 256 ; i++)
{
if(root->ptrs[i] != NULL)
{
printfunc(root->ptrs[i]);
}
}
if( root->NodeStr!= "")
cout<<"------------------------------------>"<<root->NodeStr<<endl;
}
void Node::closeFunction()
{
fin.close();
exit(0);
}
int main()
{
Node *root = new Node;
Node node;
fin.open("wordlist.txt");
while( !fin.eof() )
{
fin>>word;
cout<<endl<<word;
node.insert(word,0,root);
}
cout<<"\n\nSuccessful : Trie construction ";
while(1)
{
cout<<"\n\nEnter option :\n1.print Trie\n2.Search\n3.Exit\n\n---->";
cin>>option;
switch(option)
{
case 1:
node.printfunc(root);
break;
case 2:
cout<<"\n\nEnter string to search :";
cin>>s;
node.findword(s,0,root);
break;
case 3:
cout<<"\n\nstopped...";
node.closeFunction();
break;
default :
cout<<"Invalid options ! Try Again!!";
}
}
fin.close();
return 0;
}