Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling String

Tags:

c++

I need to write a program that scrambles a 4 letter string inputted by the user. (example TEST can be scrambled like tset, ttse etc...) Well I have a program that works but it is limited to a 4 element char array, and I want to know if there is any way to make it so I don't have to have the size pre-determined.

//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;
}
like image 682
Wil Prim Avatar asked Dec 13 '22 07:12

Wil Prim


1 Answers

I'm not sure if you want to shuffle the string once or print all permutations of the letters in the word. Both are fairly simple using the C++ Standard Library.

This first bit of code does a single random 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';
}

The following prints all permutations of the string:

#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()));
}
like image 73
Blastfurnace Avatar answered Feb 21 '23 20:02

Blastfurnace