-
Notifications
You must be signed in to change notification settings - Fork 0
/
markov.cpp
86 lines (61 loc) · 1.38 KB
/
markov.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
/*
* Markov chain random text generator.
*
* This implementation is derived from Kernighan and Pike's PoP book.
*/
#include <time.h>
#include <deque>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
const unsigned int NPREFIXES = 2;
const unsigned int MAX_OUTPUT = 10000;
typedef deque<string> Prefix;
map<Prefix, vector<string>> statetable;
const char NONWORD[] = "\n";
void add(Prefix &prefix, const string &suffix)
{
if (prefix.size() == NPREFIXES) {
statetable[prefix].push_back(suffix);
prefix.pop_front();
}
prefix.push_back(suffix);
}
void build(Prefix &prefix, istream &in)
{
string buffer;
while (in >> buffer) {
add(prefix, buffer);
}
}
void generate()
{
Prefix prefix;
for (int i = 0; i < NPREFIXES; i++) {
add(prefix, NONWORD);
}
srand(time(NULL));
for (int i = 0; i < MAX_OUTPUT; i++) {
vector<string> &suffix = statetable[prefix];
const string &word = suffix[rand() % suffix.size()];
if (word == NONWORD) {
break;
}
cout << word << endl;
prefix.pop_front();
prefix.push_back(word);
}
}
int main()
{
Prefix prefix;
for (int i = 0; i < NPREFIXES; i++) {
add(prefix, NONWORD);
}
build(prefix, cin);
add(prefix, NONWORD);
generate();
return 0;
}