-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboggleutil.cpp
executable file
·110 lines (73 loc) · 2.02 KB
/
boggleutil.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
#include "boggleutil.h"
#include <stdio.h>
#include <iostream>
using namespace std;
/**
* Constructor initializes root's properties to false and null
*/
Trie::Trie(){
root = new TrieNode;
root->isEnd = false;
//initialize null array
for(int i=0; i<26; i++){
delete root->childIndex[i];
root->childIndex[i]=NULL;
}
}
/**
* Helper function for buildLexicon. Takes in a string and inserts it into * the trie which is made up struct TrieNodes
*/
void Trie::insert(string word){
if(word.empty())
return;
//make sure word to be inserted is valid
for(int i=0; i < (int)word.size(); i++ ){
if(word[i]<97 || word[i]>122)
return;
}
TrieNode *current = root;
//loop through the word and create a trie for each child needed
for(int i=0; i<(int)word.size(); i++){
//create child for previously unassigned letter
if (current != NULL){
if( current->childIndex[((int)word[i]-97)] == NULL ){
TrieNode *child = new TrieNode();
current->childIndex[((int)word[i]-97)]=child;
current = child;
}else{
current=current->childIndex[(int)word[i]-97];
}
}
}
//end of a word is reached
current->isEnd = true;
return;
}
/**
* Helper function for buildLexicon. Takes in a string and determines if
* the string is located in the trie.
* Returns true if string present and false otherwise
*/
bool Trie::search(string word){
if(word.empty())
return false;
TrieNode *current = root;
if(word.size()<3)
return false;
for(int i=0; i< word.size(); i++){
if((int)word[i]<65 || (int)word[i]>90)
word[i]=tolower(word[i]);
}
for(int i=0; i < (int)word.size(); i++){
if((int)word[i]<97 || (int)word[i]>122)
return false;
if (current != NULL){
if(current->childIndex==NULL)
return false;
if(current->childIndex[(int)word[i]-97] == NULL)
return false;
current = current->childIndex[(int)word[i]-97];
}
}
return current->isEnd;
}