这是一个简单的未经测试的 C++ 程序,它通过以 Base 26 计数来创建单词:
#include <string>
#include <iostream>
int main(void)
{
//----------------------------------------------------------
// Print permuations of strings of letters up to length 5.
// Use base 26 arithmetic.
//----------------------------------------------------------
const unsigned int MAX_ITERATIONS = 26 * 26 * 26 * 26 * 26;
std::string word = "A";
for (unsigned int i = 0; i < MAX_ITERATIONS; ++i)
{
//------------------------------------------------------
// Print the word
//------------------------------------------------------
std::cout << word << std::endl;
//------------------------------------------------------
// Increment the word, using base 26 arithmetic.
// A, B, C, ..., Z.
// AA, BA, CA, ..., ZA, AB, BB, CB, DB, ..., ZZ.
// AAA, BAA, CAA, ..., ZAA, ABA, BBA, CBA, DBA, ..., ZZZ.
//------------------------------------------------------
bool carry_generated = false;
unsigned int digit = 0;
do
{
carry_generated = false;
if (word[digit] < 'Z')
{
++word[digit];
break;
}
word[digit++] = 'A';
if (word.length() == digit)
{
word += "A";
break;
}
carry_generated = true;
} while (carry_generated && (digit < 5));
}
return 0;
}
可以通过在打印前检查单词列表(也称为字典)来减少打印的单词数。如果单词在单词列表中,则打印它。
字长为 29 的最大问题是表示数量。数量超出了标准 C++ 无符号整数的范围。需要使用 Big Int 库。 下一个问题是处理每个组合所需的时间。 每次迭代将数量乘以 1 微秒(一种更坏的情况)并减少到天、小时、分钟和秒。也许可能需要几年时间。