2014-05-14 5 views
3

문자열의 길이는 2에서 7 자까지 다양합니다. 나는 7 문자까지 만들고 모든 순열을 컨테이너에 저장하기 위해 *를 채워야합니다. 또한 세 개 이상의 연속 *을 허용 할 수 없습니다 (예 : ABCD ***이 컨테이너에 푸시되지 않음). 또한 문자의 순서는 변경할 수 없습니다. 예를 들어순열을 사용한 문자열 조작

, 문자열 'ABCDEF' '*'가질 수 다음 순열 가득 :

ABCDEF* 
ABCDE*F 
ABCD*EF 
ABC*DEF 
AB*CDEF 
A*BCDEF 
*ABCDEF 

문자열 'ABCD' '*'다음 순열을 가질 수있다 (참고로 가득 : ABCD * 이 3 연속 있기 때문에 ** 허용되지 '*') :

ABC*D** 
ABC**D* 
AB*CD** 
AB*C*D* 
AB*C**D 
... 
**A*BCD 

(... 총 30 개 항목

내가이 작업을 수행하는 프로그램을 작성하려고) 컨테이너에 푸시됩니다. 문자열이 2 자이면 2 회 반복해야합니다. 예 :

void loop_two_times(const std::string & str = "AB") 
{ 
    for (int i = 0; i < 7; i++) 
    { 
     for (int j = i+1; j < 7; j++) 
     { 
      std::string ustring = get7StarsString(); // this string will contain 7 stars 
      ustring[i] = str[0]; 
      ustring[j] = str[1]; 

      if (!tooMuchStars(ustring)) 
      { 
       permutations.push_back(ustring); 
      } 
      else {} // do nothing 
     } 
    } 
} 

문자열이 N 자 길이이면 N 번 반복해야합니다. 그러나 문자 수를 확인하고 2,3,4,5,6 회 반복하는 함수를 작성하고 싶지 않습니다. 예 :

switch (numOfChars) 
{ 
    case 2: loop_two_times(); break; 
    case 3: loop_three_times(); break; 
    case 4: loop_four_times(); break; 
    case 5: loop_five_times(); break; 
    case 6: loop_six_times(); break; 
} 

이 기능을 어떻게 효과적으로 구현할 수 있습니까?

감사합니다.

답변

2

는 다음을 사용할 수 있습니다 : 그것은 작동 (https://ideone.com/L209jH)

// return a string with '0' replaced with letter, and '1' with '*'. 
std::string convert(const std::string& order, const std::string& s) 
{ 
    std::string res; 
    std::size_t pos = 0; 
    for (std::size_t i = 0; i != order.size(); ++i) { 
     if (order[i] == '1') { 
      res += '*'; 
     } else { 
      res += s[pos++]; 
     } 
    } 
    return res; 
} 

void print_combinaison(const std::string& msg) 
{ 
    std::string s(msg.size(), '0'); 
    s.resize(7, '1'); 
    // s is a string of 7 letter with '0' (representing letter) 
    // and '1' representing '*' 
    // initial value of s is one of 0000000, 0000001, 0000011, 0000111, 
    // 0001111, 0011111, 0111111 or 1111111. 
    do 
    { 
     if (s.find("111") != std::string::npos) continue; 

     std::cout << convert(s, msg) << std::endl; 
    } while (std::next_permutation(begin(s), end(s))); 
} 
+0

을! 매우 영리하고 매우 효율적입니다 :) – chesschi