【问题标题】:how to use next_permutation如何使用 next_permutation
【发布时间】:2013-05-21 22:08:52
【问题描述】:

我正在尝试安排井字游戏。所以我有以下代码:

// 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()) );

但它只输出一次原始字符串。我假设每个角色都必须是独一无二的。我有什么办法可以做到这一点?

【问题讨论】:

  • 尝试从相反的顺序开始,next_permutation 按字典顺序生成它们,而你所拥有的是字典顺序的最后一个。

标签: c++ permutation


【解决方案1】:

std::next_permutation 按字典顺序返回下一个排列,如果生成了第一个排列(按该顺序),则返回 false。

由于您以 ("xxxxxoooo") 开头的字符串实际上是该字符串字符按字典顺序的最后一个排列,因此您的循环会立即停止。

因此,您可以在开始循环调用next_permutation() 之前尝试对moves 进行排序:

std::string moves = "xxxxxoooo";
sort(begin(moves), end(moves));

while (std::next_permutation(begin(moves), end(moves)))
{
    std::cout << moves << std::endl;
}

这是live example。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多