I want to print out all possible words (generating input for testing of other algorithm) of length n
, containing the (maybe duplicated) letters from 'a'
to 'a' + n
.
I tried to do the following:
#include <iostream>
#include <string>
#include <algorithm>
using size_type = std::size_t;
using symbol_type = std::string;
using char_type = typename symbol_type::value_type;
template< size_type n >
struct test
{
static_assert(!(size_type('z' - 'a') + 1 < n));
void
print(symbol_type const & _symbol) const
{
for (size_type i = 0; i < n; ++i) {
std::cout << _symbol.substr(i * n, n) << std::endl;
}
std::cout << std::endl;
}
bool
operator () () const
{
symbol_type mishmash_;
for (size_type i = 0; i < n; ++i) {
mishmash_.append(symbol_type(n, char_type('a' + i)));
}
print(mishmash_);
while (std::next_permutation(std::begin(mishmash_), std::end(mishmash_))) {
print(mishmash_);
}
return true;
}
};
int
main()
{
test< 3 > const test_{};
if (test_()) {
std::cout << "Succes!" << std::endl;
return EXIT_SUCCESS;
} else {
std::cerr << "Failure!" << std::endl;
return EXIT_FAILURE;
}
}
But there are duplicates of words. How to achive the desired in most optimal way?
It's conceptually the same task as iterating the numbers from 0000000... (n times) to 999999... - just doing a base-n conversion: i.e. increment a number and each time you want the next "value", use % n + 'a'
to extract a "digit" and /= n
to prepare to get the next one....
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句