我试图弄清楚如何根据给定的字符串生成C ++中的单词列表(类似于crunch wordlist的工作方式)
我是C ++的新手,只是让程序一次列出一个字符。
我一直在网上搜索相当一段时间没有太多运气,除了找到O(n ^ 2)并没有太多想法如何将它实现到程序中。
代码:
int main() {
string characters = "abcde";
int length = 5;
string word = "";
for(int i = word.length(); i <= length; i++) {
for(int l = 0; l < characters.length(); l++) {
word += characters[l];
cout << word << "\n";
}
}
return 0;
}
结果:
a
b
c
d
e
通缉结果:http://pastebin.com/tgyUtKfA
结果片段:
a
b
c
d
e
aa
ab
ac
ad
ae
ba
bb
bc
bd
be
ca
cb
cc
cd
ce
da
db
dc
dd
de
ea
eb
ec
ed
ee
aaa
(最终结果遵循该模式,直到&#34; eeeee&#34;)
答案 0 :(得分:0)
#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<string> make_permutations(int length) {
if (length == 0) {
return vector<string>{};
}
vector<string> results;
vector<string> children = make_permutations(length - 1);
for (char letter = 'a'; letter <= 'z'; letter++) {
results.emplace_back(1, letter);
for(auto child : children) {
results.push_back(std::string(1, letter) + child);
}
}
return results;
}
int main()
{
auto results = make_permutations(2);
for(auto s : results) cout << s << endl;
}
答案 1 :(得分:0)
// dyndict.cpp
#include <iostream>
#include <string>
#include <vector>
#include <mutex>
using namespace std;
class CDynDict
{
public:
CDynDict();
~CDynDict();
void Reset(const string& source, int minout, int maxout);
bool Next(string& str);
private:
string _source;
int _outlen, _minout, _maxout;
vector<int> _vecdict;
mutex _mutex;
};
CDynDict::CDynDict()
{
}
CDynDict::~CDynDict()
{
}
void CDynDict::Reset(const string& source, int minout, int maxout)
{
unique_lock<mutex> locker(_mutex);
_source = source;
_minout = minout;
_maxout = maxout;
if (_minout > _maxout)
swap(_minout, _maxout);
_outlen = minout;
_vecdict.resize(_outlen);
}
bool CDynDict::Next(string& str)
{
int i = 0, carry = 1;
int lsrc = _source.length();
unique_lock<mutex> locker(_mutex);
if (_vecdict.size() == 0 || _outlen > _maxout)
return false;
str.clear();
while (i <_outlen) str += _source[_vecdict[i++]];
for (i = _outlen-1; i >= 0; i--)
{
if (carry == 0) break;
_vecdict[i] += carry;
carry = _vecdict[i] / lsrc;
if (carry > 0 && i > 0) _vecdict[i] %= lsrc;
}
if (_vecdict[0] >= lsrc)
{
_vecdict.resize(++_outlen);
_vecdict.assign(_outlen, 0);
}
return true;
}
int main(int argc, char* argv[])
{
CDynDict dict;
string str;
dict.Reset("abcde", 1, 4);
while (dict.Next(str))
cout << str << endl;
return 0;
}