#include <iostream>
#include <fstream>
#include <vector>
using
namespace
std;
class
Wordpair
{
private
:
vector<string> suffix;
vector<
int
> freq;
public
:
string prefix;
int
length;
Wordpair()
{
this
->prefix =
""
;
this
->length = 0;
}
Wordpair(string prefix, string suffix)
{
this
->prefix = prefix;
this
->suffix.push_back(suffix);
this
->freq.push_back(1);
this
->length = 1;
}
int
hasRecord(string word);
void
pushRecord(string word);
string maxFreq();
};
int
Wordpair::hasRecord(string word)
{
for
(
int
i = 0; i <
this
->length; i++)
{
if
(word ==
this
->suffix[i])
{
return
i;
}
}
return
-1;
}
void
Wordpair::pushRecord(string word)
{
int
num =
this
->hasRecord(word);
if
(num == -1)
{
this
->suffix.push_back(word);
this
->freq.push_back(1);
this
->length++;
}
else
{
this
->freq[num]++;
}
}
string Wordpair::maxFreq()
{
int
maxIndex = 0;
int
maxFreq =
this
->freq[0];
for
(
int
i = 1; i < length; i++)
{
if
(freq[i] > maxFreq)
{
maxIndex = i;
maxFreq = freq[i];
}
}
return
this
->suffix[maxIndex];
}
string getArticle(string path)
{
ifstream file(path);
string temp, article =
""
;
if
(!file.is_open())
{
cout <<
"读取文件出错!"
<< endl;
return
""
;
}
while
(getline(file, temp))
{
article.append(temp);
}
file.close();
return
article;
}
void
createPrefix(vector<Wordpair> &pairList, string prefix, string suffix)
{
Wordpair temp(prefix, suffix);
pairList.push_back(temp);
}
void
articleToWordpair(vector<Wordpair> &pairList, string &article,
int
prefixLen,
int
suffixLen)
{
for
(
int
i = 0; i < article.size() / ((prefixLen + suffixLen) * 3); i++)
{
string slide, prefixTemp, suffixTemp;
bool
found =
false
;
slide = article.substr(i * (prefixLen + suffixLen) * 3, (prefixLen + suffixLen) * 3);
prefixTemp = slide.substr(0, prefixLen * 3);
suffixTemp = slide.substr(prefixLen * 3, suffixLen * 3);
for
(
auto
&pair : pairList)
{
if
(prefixTemp == pair.prefix)
{
pair.pushRecord(suffixTemp);
found =
true
;
break
;
}
}
if
(!found)
{
createPrefix(pairList, prefixTemp, suffixTemp);
}
}
}
string generateArticle(vector<Wordpair> &pairList, string startWord,
int
prefixLen,
int
suffixLen)
{
string article = startWord, prefix = startWord, suffix;
while
(1)
{
bool
found =
false
;
for
(
auto
&pair : pairList)
{
if
(prefix == pair.prefix)
{
suffix = pair.maxFreq();
found =
true
;
break
;
}
}
if
(!found)
{
return
article;
}
article.append(suffix);
prefix = suffix;
}
}
int
main()
{
string path, article, startword, newarticle;
vector<Wordpair> pairList;
int
prefixLen, suffixLen;
path =
"article.txt"
;
cout <<
"请输入前缀长度、后缀长度和起始词,以空格分隔:"
<< endl;
cin >> prefixLen >> suffixLen >> startword;
article = getArticle(path);
articleToWordpair(pairList, article, prefixLen, suffixLen);
newarticle = generateArticle(pairList, startword, prefixLen, suffixLen);
cout << newarticle;
return
0;
}