2016-08-05 1 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입니다. –

관련 문제