打印出每个阵列的所有可能性?

时间:2016-08-05 05:07:54

标签: c++

我基本上是在尝试在网络上发现的一系列在线问题而且我已经被困在这个人身上2个小时了。

string array1[3] = {"He", "She", "They"};
string array2[3] = {"Ran", "Ate", "Sat"};

我也使用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];

在不多次输出相同输出的情况下获取所有可能输出的算法是什么?

示例:He Ran, He Ate, He Sat, She Ran, She Ate, She Sat, They Ran, They Ate, They Sat ...但所有随机化?

1 个答案:

答案 0 :(得分:1)

您有九种可能的组合。创建一个索引为0 - 8的数组。使用std::random_shuffle随机调整数组。然后,使用数组的元素作为组合的索引。

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

完成计划:

#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;
}

示例输出:

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