Reputation: 2079
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;
}
Upvotes: 5
Views: 20819
Reputation: 18652
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()));
}
Upvotes: 15
Reputation: 7564
You can use an std::string instead of a char[4]. (Strings are always preferable to char[] anyway). Your code would then be:
string str; 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<str.size();i++){ // iteration through one full loop in array
And for a better way to shuffle the string check out:
std::next_permutation
Upvotes: 0
Reputation: 426
There's an easier way to scramble a string of length N.
Iterate through the string from character 0 -> n-1
.
Select two random indices i,j
(via random(n)
) at each iteration, and swap those two indices.
You can prove that that will be a uniformly random scrambling.
Upvotes: 0