okay14 - 1 year ago 65

C++ Question

I'm basically trying a bunch of online problems that I found on the web and I've been stuck on this guy for 2 hours.

`string array1[3] = {"He", "She", "They"};`

string array2[3] = {"Ran", "Ate", "Sat"};

I'm also using

`srand(time(NULL));`

`string array1[3] = {"He", "She", "They"};`

string array2[3] = {"Ran", "Ate", "Sat"};

srand(time(NULL));

int random1 = rand() % 3;

int random2 = rand() % 3;

cout << array1[random1] << " " << array2[random2];

What is the algorithm for getting all possible outputs without outputting the same output more than once?

Example:

`He Ran, He Ate, He Sat, She Ran, She Ate, She Sat, They Ran, They Ate, They Sat`

Answer Source

You have nine possible combinations. Create an array that has the indices `0`

-`8`

. Use `std::random_shuffle`

to shuffle the array randomly. Then, use the elements of the array as indices to the combinations.

```
int indices[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
std::random_shuffle(indices, indices+9);
```

Complete Program:

```
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <string>
int main()
{
std::string array1[3] = {"He", "She", "They"};
std::string array2[3] = {"Ran", "Ate", "Sat"};
std::srand(std::time(NULL));
int indices[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
std::random_shuffle(indices, indices+9);
for ( auto index : indices )
{
int i = index/3;
int j = index%3;
std::cout << array1[i] << " " << array2[j] << ", ";
}
std::cout << std::endl;
}
```

Sample output:

```
They Sat, They Ran, He Sat, He Ate, She Ate, He Ran, They Ate, She Ran, She Sat,
```