Emilia
Emilia

Reputation: 35

Writing a C++ program to print the letters of a string in a chaotic order

What I'm trying to do is this:

So far I've written this code, but the problem is that sometimes the randomly generated numbers are the same, so it might print the same indexes(letters) twice or more times:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    
    cout << "Say something: ";
    string text;
    getline(cin, text);
    
    cout << "\nChaotic text: ";
    
    srand(time(0));
    for(unsigned int j=0; j<text.length(); j++){
        int randomLetter = rand()%text.length(); 
        
        cout << text.at(randomLetter);
    }

    return 0;
}

Can anyone help me fix it?

Upvotes: 0

Views: 125

Answers (2)

a.koptan
a.koptan

Reputation: 1248

Instead of calling rand() one time, which can generate an index you have called before, you can keep generating a new index while keeping tracking of all generated indices in a hashtable.

std::unordered_map<int, bool> done;
for (unsigned int j = 0; j < text.length(); j++) {
    int randomLetter = rand() % text.length();

    while (done[randomLetter] == true) // while it's been marked as finished, generate a new index.
        randomLetter = rand() % text.length();

    cout << text.at(randomLetter);
    done[randomLetter] = true; // mark it as finished.
}

Alternatively, you can use std::random_shuffle instead, which should save you the hassle.

std::random_shuffle (text.begin(), text.end());
std::cout << text << '\n';

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

You can use std::shuffle (since C++11):

#include <iostream>
#include <string>
#include <random>
#include <algorithm>

using namespace std;

int main(){
    
    cout << "Say something: ";
    string text;
    getline(cin, text);
    
    cout << "\nChaotic text: ";

    std::mt19937 g(time(0));
 
    std::shuffle(text.begin(), text.end(), g);
    cout << text;

    return 0;
}

Or std::random_shuffle (if you are using old specification):

#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>

using namespace std;

int main(){
    
    cout << "Say something: ";
    string text;
    getline(cin, text);
    
    cout << "\nChaotic text: ";

    srand(time(0));
 
    std::random_shuffle(text.begin(), text.end());
    cout << text;

    return 0;
}

Upvotes: 1

Related Questions