初の試み:
#include <vector>
#include <algorithm>
#include <iostream>
std::vector<std::vector<int>> all_permutations(std::vector<int> input)
{
std::vector<std::vector<int>> result;
std::sort(begin(input), end(input));
input.erase(std::unique(begin(input), end(input)), end(input));
do {
result.push_back(input);
} while(std::next_permutation(begin(input), end(input)));
return result;
}
template<class T>
void emit(std::ostream& os, std::vector<T> const& v)
{
os << " [";
const char* sep = " ";
for (auto&& x : v) {
os << sep << x;
sep = ", ";
}
os << "]\n";
}
template<class T>
void emit(std::ostream& os, std::vector<std::vector<T>> const& v)
{
os << "[\n";
for (auto&& x : v) {
emit(os, x);
}
os << "]\n";
}
int main()
{
emit(std::cout, all_permutations({ 1, 2, 3 }));
}
予想される出力。
[
[ 1, 2, 3]
[ 1, 3, 2]
[ 2, 1, 3]
[ 2, 3, 1]
[ 3, 1, 2]
[ 3, 2, 1]
]
今、プラスとマイナスのコードを追加します。
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
std::vector<std::vector<int>> all_permutations(std::vector<int> input)
{
std::vector<std::vector<int>> result;
std::sort(begin(input), end(input));
input.erase(std::unique(begin(input), end(input)), end(input));
do {
result.push_back(input);
} while(std::next_permutation(begin(input), end(input)));
return result;
}
template<class T>
void emit(std::ostream& os, std::vector<T> const& v)
{
os << " [";
const char* sep = " ";
for (auto&& x : v) {
os << sep << x;
sep = ", ";
}
os << "]\n";
}
template<class T>
void emit(std::ostream& os, std::vector<std::vector<T>> const& v)
{
os << "[\n";
for (auto&& x : v) {
emit(os, x);
}
os << "]\n";
}
std::vector<int> plus_and_minus(std::vector<int> v)
{
std::vector<int> inverse;
inverse.reserve(v.size());
std::transform(begin(v), end(v), back_inserter(inverse), [](auto&& x) { return -x; });
v.insert(end(v), begin(inverse), end(inverse));
sort(begin(v), end(v));
inverse.erase(unique(begin(v), end(v)), end(v));
return v;
}
int main()
{
emit(std::cout, all_permutations(plus_and_minus({ 1, 2, 3 })));
}
予想:
[
[ -3, -2, -1, 1, 2, 3]
[ -3, -2, -1,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1, -2, 2, -1, 3]
[ -3, 1, -2, 2, 3, -1]
[ -3, 1, -2, 3, -1, 2]
[ -3, 1, -2, 3, 2, -1]
[ -3, 1, -1, -2, 2, 3]
[ -3, 1, -1, -2, 3, 2]
[ -3, 1, -1, 2, -2, 3]
[ -3, 1, -1, 2, 3, -2]
[ -3, 1, -1, 3, -2, 2]
[ -3, 1, -1, 3, 2, -2]
[ -3, 1, 2, -2, -1, 3]
[ -3, 1, 2, -2, 3, -1]
[ -3, 1, 2, -1, -2, 3]
[ -3, 1, 2, -1, 3, -2]
[ -3, 1, 2, 3, -2, -1]
[ -3, 1, 2, 3, -1, -2]
[ -3, 1, 3, -2, -1, 2]
[ -3, 1, 3, -2, 2, -1]
[ -3, 1, 3, -1, -2, 2]
[ -3, 1, 3, -1, 2, -2]
[ -3, 1, 3, 2, -2, -1]
[ -3, 1, 3, 2, -1, -2]
[ -3, 2, -2, -1, 1, 3]
[ -3, 2, -2, -1, 3, 1]
[ -3, 2, -2, 1, -1, 3]
[ -3, 2, -2, 1, 3, -1]
[ -3, 2, -2, 3, -1, 1]
[ -3, 2, -2, 3, 1, -1]
[ -3, 2, -1, -2, 1, 3]
[ -3, 2, -1, -2, 3, 1]
[ -3, 2, -1, 1, -2, 3]
...etc
http://coliru.stacked-crooked.com/a/82a4c5784dc0070d
std :: next_permuation()? –