2016-08-05 6 views
-1

私は基本的にウェブで見つけたオンラインの問題をたくさん試しています。私はこの男に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 ...しかし、すべてランダム化されていますか?

+2

[あなたはこれを読むことをお勧めします](http://dilbert.com/strip/2001-10-25 ) –

+0

@uhohsomebodyneedsapupperそれが私を笑わせました。 :D – okay14

+2

なぜ特定の出力が必要な場合は乱数を使用しますか?乱数はランダムであり、毎回異なる出力であり、したがって異なる結果である。 – Rakete1111

答えて

1

可能な組み合わせは9種類あります。インデックスが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, 
+0

'random_shuffle'は非推奨ですか? –

+0

あなたは天才です!これは最高です!明確な説明をありがとう! – okay14

+0

@uhohsomebodyneedsapupperはい、それはC++ 14です。 –

関連する問題