-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8_MakeaSentence.cpp
125 lines (106 loc) · 2.45 KB
/
8_MakeaSentence.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
//
// Created by Daisy on 2020/11/17.
//
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include "7_Use library/using library.h"
using namespace std;
typedef vector<string> Rule;
typedef vector<Rule> Rule_collection;
typedef map<string, Rule_collection> Grammar;
Grammar read_grammar(istream& in)
{
Grammar ret;
string line;
int line_num = 0;
while (getline(in,line) && line_num<14)
{
line_num += 1;
vector<string> entry = split(line);
if (!entry.empty())
ret[entry[0]].push_back(Rule(entry.begin()+1, entry.end()));
}
return ret;
}
bool bracketed(const string& s)
{
return s.size()>1 && s[0] == '<' && s[s.size()-1] == '>';
}
// 将RAND_MAX 分成 n 个区间,随机抽取整数,看随机数处于哪个位置,从而得到小于n的结果
int nrand(int n)
{
if (n <= 0|| n> RAND_MAX)
throw domain_error("Argument ti nrand is out of range");
const int bucket_size = RAND_MAX/n;
int r;
do r = rand()/bucket_size;
while (r>=n);
return r;
}
void gen_aux(const Grammar& g, const string& word, vector<string>& ret)
{
if (!bracketed(word))
{
ret.push_back(word);
}
else
{
auto it = g.find(word); //找到 sentence 开头的规则
if (it == g.end())
{
cout << "word" << word << endl;
throw logic_error("empty rule");
}
const Rule_collection c = it->second; // 重定向所有规则
const Rule r = c[nrand(c.size())]; //随机采用一个规则
for (auto i = r.begin(); i!= r.end();++i)
gen_aux(g, *i, ret);
}
}
vector<string> gen_sen(const Grammar& g)
{
vector<string> ret;
gen_aux(g, "<sentence>", ret);
return ret;
}
void outputSentence(vector<string> sentence){
auto it = sentence.begin();
if (!sentence.empty())
{
cout << *it;
++it;
}
while (it != sentence.end())
{
cout<< " " << *it ;
++it;
}
cout << endl;
}
int SENmain()
{
Grammar g = read_grammar(cin);
for(int i=0;i!=10;++i)
{
vector<string> sentence = gen_sen(g);
outputSentence(sentence);
}
return 0;
}
//<none> cat
//<none> dog
//<none> table
//<np> <none>
//<np> <adj> <none>
//<adj> large
//<adj> brown
//<adj> absurd
//<verb> jumps
//<verb> sits
//<pos> on the stairs
//<pos> under the sky
//<pos> where it wants
//<sentence> the <np> <verb> <pos>
// end-of-file