随机串

Wil*_*rim 2 c++

我需要编写一个程序来扰乱用户输入的4个字母的字符串.(示例TEST可以像tset,ttse等一样加扰......)我有一个程序可以工作,但它仅限于一个4元素字符数组,我想知道是否有任何方法可以做到这一点我不喜欢必须具有预先确定的大小.

//4 letter word scrambler (ex. test tets tset...)
int counter=0;
int main(int argc, char* argv[])
{
    char str[4];
    cout << "Please enter a  word: "; //ask for input
    cin >> str;
    counter+=1; // set counter to 1 
    cout << counter << " " << str << endl;
    for (int i=0;i<3;i++){// iteration through one full loop in array
        swap(str[i], str[i+1]); //swap two elements as iterates through array
        counter+=1;//add 1 to counter each time
        cout <<counter<<" "<< str << endl;
    }
    for (int i=0;i<3;i++){
        swap(str[i], str[i+1]);
        counter+=1;
        cout << counter<< " " << str << endl;
    }
    for (int i=0;i<3;i++){
            swap(str[i], str[i+1]);
        counter+=1;
        cout << counter << " " << str << endl;
    }
    for (int i=0;i<2;i++){
            swap(str[i], str[i+1]);
        counter+=1;
        cout << counter << " " << str << endl;
    }

    system("PAUSE");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bla*_*ace 9

我不确定你是想要将字符串改组一次还是打印字母中所有字母的排列.使用C++标准库时,两者都相当简单.

这第一段代码执行单个随机shuffle:

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    cout << "Please enter a  word: "; //ask for input
    cin >> str;
    random_shuffle(str.begin(), str.end());
    cout << str << '\n';
}
Run Code Online (Sandbox Code Playgroud)

以下打印字符串的所有排列:

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    cout << "Please enter a  word: "; //ask for input
    cin >> str;
    sort(str.begin(), str.end());
    do {
        cout << str << '\n';
    } while (next_permutation(str.begin(), str.end()));
}
Run Code Online (Sandbox Code Playgroud)