1

I hope this is a very simple question, but how can you random a string within a array

For example, for vaules ill do this

`

#include <cstdlib> 
#include <iostream>
using namespace std;
int main() 
{
srand ( time(NULL) ); //initialize the random seed


const char arrayNum[4] = {'1', '3', '7', '9'};

int RandIndex = rand() % 4;
int RandIndex_2 = rand() % 4;
int RandIndex_3 = rand() % 4;
int RandIndex_4 = rand() % 4; //generates a random number between 0 and 3

cout << arrayNum[RandIndex] << endl;;
system("PAUSE");
return 0;
}    `

how can i apply this if there is string within the arraynum

I have come across something like this in my serach for an answer though

std::string textArray[4] = {"Cake", "Toast", "Butter", "Jelly"};

but all I come across is a hex answer which does not change on it's own. so therefore I am going to assume it is probably not even randomized.

2
  • 1
    std::random_shuffle would be a better choice if you don't want duplicates. As it is, you could very well pick the same one twice. Commented Jan 1, 2013 at 8:39
  • @jackson chen : Welcome to SO. You may accept Rapptz answer (by checking the tick mark on the left of the answer), if it solves your problem . Commented Jan 1, 2013 at 8:48

1 Answer 1

4

You could use std::random_shuffle

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

int main() {
    std::srand(std::time(0));
    std::string str = "123456212";
    std::random_shuffle(str.begin(),str.end());
    std::cout << str;
}

Possible output: 412536212

If you're using C++11, you can do the same with C-Style arrays like so:

int main() {
    std::srand(std::time(0));
    std::string str[4] = {"Cake", "Toast", "Butter", "Jelly"};
    std::random_shuffle(std::begin(str),std::end(str));
    for(auto& i : str)
        std::cout << i << '\n';
}

Or if you're lacking a C++11 compiler you can do the alternative:

int main() {
    std::srand(std::time(0));
    std::string str[4] = {"Cake", "Toast", "Butter", "Jelly"};
    std::random_shuffle(str, str + sizeof(str)/sizeof(str[0]));
    for(size_t i = 0; i < 4; ++i) 
        std::cout << str[i] << '\n';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.