簡體   English   中英

排列問題

[英]Permutation Issue

因此,我這里有一個程序,該程序應該在屏幕上顯示用戶輸入的單詞的排列,該排列的長度可以是4到10個字符,並且應該與單詞中的字母一樣多。 我幾乎可以取得圓滿成功,但是有一個問題。 當它打印排列時,在第一個大約2個排列之后,它開始不再使用所有字母和/或相同的字母兩次。

例如,如果用戶輸入的單詞是“ bill”,則輸出如下:

利比爾

第四個顯然是不正確的。 對於具有更多字母的單詞,問題更加明顯。 我需要它僅使用一次它的字母。 如何在我的代碼中解決這個問題? 這是我的代碼。

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()));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM