排列问题

Permutation Issue

本文关键字:问题 排列      更新时间:2023-10-16

所以我这里有一个程序,它应该打印到用户输入单词的排列,长度可以是 4 到 10 个字符,并且应该有与单词中的字母一样多的排列。我几乎取得了完全的成功,但有一个问题。当它打印排列时,在第一个大约 2 个排列之后,它开始不使用所有字母和/或同一个字母两次。

例如,如果用户输入的单词是"bill",则输出如下:

llib illb ibll lbii

第四个显然是不正确的。对于具有更多字母的单词,问题更为明显。我需要它只使用它有一次的字母。如何在代码中解决此问题?这是我的代码。

int main(void)
{
string word;
string randword;
string reverse;
int length;
int i = 0;
int j = 0;
string randCH;
    cout << "Enter any word 4 to 10 letters in length: ";
    cin >> word;
    //Checks if word is less than 4 or greater than 10
    while (1)
    {
        /*The code here is in the final program and I know it works. The problem is not here*/
    }
    length = word.length();
    //Uses reverse function
    reverse = reverseit(word);
    /*reverseit is a function outside of main that makes the word backwards*/
    //Prints all permutations
    cout << endl << reverse << "     ";
    for (i = 0; i < word.length() - 1; i++)
    {
        for (j = 0; j < word.length(); j++)
        {
            randCH = word.substr(rand() % length, 1);
            cout << randCH;
        }
        cout << "     ";
    cout << endl;

您可以使用已经构建的std::next_permutation来实现此目的:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    string word;
    cin >> word;
    sort(word.begin(),word.end());
    do {
        cout << word <<endl;
    } while(next_permutation(word.begin(),word.end()));
}