오늘도 지난 시간에 이어서, 고등학교 수학을 복습해봅시다. *^^*
이번엔 수열(數列; series; progression)이 아니라 순열(順列, permutation)을 구하는 방법입니다.
STL의 순열 알고리듬은 next_permutation과 prev_permutation이 있습니다.
예제는 다음과 같습니다.
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
#include <algorithm>
#include <iterator>
//---------------------------------------------------------------------------
using namespace std;
int main()
{
char digits[] = "0123456789";
ostreambuf_iterator<char> out(cout); // 단순히 char만을 출력할 때는 ostreambuf_iterator를 쓰세요.
const int max_length = 5; // 이걸 10으로 하면 엄청 오래걸립니다. O(n!) 알고리듬이니까요.
// 결과가 필요하다면 파일로 redirection해서 보시길...
for (int i = 2; i <= max_length; ++i) {
do {
copy(&digits[0], &digits[i], out);
cout.put('\n');
} while (next_permutation(&digits[0], &digits[i]));
cout.put('\n');
}
return 0;
}
결과는 다음과 같습니다.
01
10
012
021
120
...
0123
0132
...
43201
43210
위와 같이 내림차순으로 정렬되는 순열이 나오면 모든 순열이 다 출력되었다는 의미로
next_permutation이 false를 반환하게 되고, 루프가 종료되는 것이죠.
|