11 c++ permutation
我正在尝试安排tic tac toe board.所以我有以下代码:
// 5 turns for x if x goes first
std::string moves = "xxxxxoooo";
do {
std::cout << moves << std::endl;
} while ( std::next_permutation(moves.begin(), moves.end()) );
Run Code Online (Sandbox Code Playgroud)
但它只输出一次原始字符串.我假设每个角色都必须是唯一的.我能做到这一点的方式是什么?
And*_*owl 18
std::next_permutation以字典顺序返回下一个排列,并false在生成第一个排列(按此顺序)时返回.
由于您以("xxxxxoooo")开头的字符串实际上是字典顺序中该字符串字符的最后一个排列,因此您的循环会立即停止.
因此,您可以moves在开始调用next_permutation()循环之前尝试排序:
std::string moves = "xxxxxoooo";
sort(begin(moves), end(moves));
while (std::next_permutation(begin(moves), end(moves)))
{
std::cout << moves << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例.