Repository navigation
Expand file tree
/
Copy pathdictionary.cpp
More file actions
80 lines (65 loc) · 2.44 KB
/
Copy pathdictionary.cpp
File metadata and controls
80 lines (65 loc) · 2.44 KB
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
/******************************************************************
Title: dictionary.cpp
Author: Erin Williams
Date Created: 5/2/2017
Class: Spring 2017, CSCI 235-04, Mon & Wed 7:00pm-8:15pm
Professor: Aarsh Vora
Purpose: Assignment #3
Description: Dictionary header file
*******************************************************************/
#include <string>
#include <utility>
#include <vector>
#include <queue>
#include "trie.h"
#include "trienode.h"
#include "dictionary.h"
namespace dictwilliams {
//Returns a vector of n strings. Strings are legal words that require the
//fewest additional characters. The words are organized by lenghth, then
//alphabetically
std::vector<std::string> Dictionary::suggest(const std::string& s, int n) const {
//NEED TO WORRY ABOUT LOWERCASE/UPPERCASE
//Vector to store suggested strings
std::vector<std::string> vec;
std::string prefix = s;
//Get last node of s
triewilliams::TrieNode* node = trie_.find(prefix);
//Node/prefix string pair to store in queue
std::pair<triewilliams::TrieNode*, std::string> p(node, prefix);
//Queue to store nodes and prefix strings
std::queue<std::pair<triewilliams::TrieNode*, std::string>> q;
//Keeps track of number of words requested
int count = 0;
if(node == NULL) {
return vec;
}
//If input string is a word, push to vector
if(node->getWordMarker()) {
vec.push_back(prefix);
++count;
}
//push first pair to queue
q.push(p);
while(!(q.empty())) {
//Current node is node at front of queue
triewilliams::TrieNode* current = q.front().first;
//Prefix is second value in pair
prefix = q.front().second;
q.pop();
std::map<char, triewilliams::TrieNode*>::iterator it;
for(it = current->children().begin(); it != current->children().end(); ++it) {
//Pair is now the node pointed to by iterator and prefix + the letter key
p = std::make_pair(it->second, std::string(prefix + it->first));
q.push(p);
//Push string to vector if it is the end of a word
//and requested number of words not yet reached
if(it->second->getWordMarker() && count < n) {
vec.push_back(prefix + it->first);
++count;
}
}
}
return vec;
}
} //dictwilliams