school/cs235/lab07/mimic.cpp
2016-04-06 20:46:10 -07:00

105 lines
2.6 KiB
C++

#include "mimic.h"
mimic::mimic() {}
vector<string> parser(string input) {
vector<string> results;
string s;
for(unsigned int i = 0; i < input.length(); i++) {
char c = input[i];
if(c != ' ') {
s += c;
}
else {
if(s != "") {
results.push_back(s);
s.clear();
}
}
}
if(s != "") {
results.push_back(s);
}
return results;
}
void mimic::add_to_dmmap(string prefix, string suffix) {
bool add_test = true;
for(unsigned int i = 0; i < dmmaps.size(); i++) {
if(dmmaps[i].key == prefix) {
add_test = false;
dmmaps[i].values.push_back(suffix);
}
}
if(add_test) {
dmmaps.push_back(dmmap(prefix, suffix));
}
}
void mimic::createMap(string input) {
cout << input << endl;
vector<string> parsed_input = parser(input);
for(unsigned int i = 0; i < parsed_input.size() - 2; i++) {
string prefix;
string suffix;
prefix += parsed_input[i];
prefix += " ";
prefix += parsed_input[i+1];
suffix += parsed_input[i+2];
add_to_dmmap(prefix, suffix);
}
string prefix = parsed_input[parsed_input.size() - 2];
prefix += " ";
prefix += parsed_input[parsed_input.size() - 1];
add_to_dmmap(prefix, "THE_END");
}
vector<string> mimic::getSuffixList(string prefix) {
for(unsigned int i = 0; i < dmmaps.size(); i++) {
if(dmmaps[i].key == prefix) {
return dmmaps[i].values;
}
}
vector<string> v;
return v;
}
string mimic::generateText() {
string text;
srand (time(NULL));
if(dmmaps.size() == 0) {
return "";
}
text += dmmaps[0].key;
text += " ";
string prefix1 = dmmaps[0].key;
while(true) {
vector<string> v = getSuffixList(prefix1);
string temp = v[rand() % v.size()];
if(temp == "THE_END") {
text.erase(text.find_last_not_of(" ")+1);
return text;
}
else {
text += temp;
text += " ";
}
vector<string> prefix_vec = parser(prefix1);
prefix1 = prefix_vec[1];
prefix1 += " ";
prefix1 += temp;
}
}
ostream & operator<<(ostream & os, mimic m) {
os << "[";
for(unsigned int i = 0; i < m.dmmaps.size(); i++) {
os << "'" << m.dmmaps[i].key << "' ,";
for(unsigned int j = 0; j < m.dmmaps[i].values.size(); j++) {
os << m.dmmaps[i].values[j] << ", ";
}
}
os << "]";
return os;
}