Problem 1: print out all of the permutations of n elements:
template <typename Iterator>
void perm(Iterator begin, Iterator end, Iterator i)
{
if (i != end) {
for (auto j = i; j != end; ++j) {
exchange(i, j);
perm<Iterator>(begin, end, i + 1);
exchange(i, j);
}
}
else {
std::for_each(begin, end, [](typename boost::call_traits<typename std::iterator_traits<Iterator>::value_type>::param_type n) {
std::cout << n < " ";
}
);
std::cout << std::endl;
}
}
Problem 2: print out all of the reasonable permutations of n pairs of parenthesis.
void perm(char * begin, char * end, char * i, size_t left_count, size_t right_count)
{
if (i < end) {
size_t n = (end - begin)/2;
if (left_count <= n && right_count <= n) {
if (left_count > right_count) {
*i = ')';
perm(begin, end, i + 1, left_count, right_count + 1);
}
*i = '(';
perm(begin, end, i + 1, left_count + 1, right_count);
}
}
else {
if (left_count == right_count) {
std::for_each(begin, end, [](char c) {std::cout << c;});
std::cout << std::endl;
}
}
}
Testing code:
int main()
{
int data[] = {1, 2, 3, 4};
perm(std::begin(data), std::end(data), std::begin(data));
char buf[6];
perm(std::begin(buf), std::end(buf), std::begin(buf), 0, 0);
return 0;
}