【问题标题】:Finding permutations and combinations of elements in the array for 2 elements each查找数组中元素的排列和组合,每个元素有 2 个
【发布时间】:2018-02-05 01:00:09
【问题描述】:

我试图找到元素的排列和组合,每个元素有 2 个对象 - nC2 或 nP2。我可以通过以下代码找到组合。有什么优雅的方法来重写它吗?另外,有什么方法可以找到排列吗?以下只是一个示例,我的数据集包含近 2000 个元素。所以,速度也是一个因素。

#include <iostream>
#include <vector>
#include <string>
int main() {

  std::vector<std::string> array = {"a", "b", "c", "d", "e"};
  std::vector<std::string>::iterator it = array.begin();
  for ( ; it < array.end(); it++ ) {
    for (std::vector<std::string>::iterator it_next = it+1 ; it_next < array.end(); it_next++ ) {
        std::cout << *it << *it_next << "\n";
    }
  }
}

程序输出-

gcc 版本 4.6.3

ab 交流 广告 ae 公元前 BD 是 光盘 ce 去

【问题讨论】:

  • std::next_permutation函数。
  • 它工作正常,考虑使用Code Review
  • @Ron ... 为什么要删除 repl 链接?
  • 请注意这里有两个独立的问题: 1. 无论如何要改进组合? 2.如何计算排列?
  • @Ron 明白并说得通。仍在学习规则:)

标签: c++ algorithm


【解决方案1】:

相对于您的初始组合代码,您可以通过使用 [] 而不是迭代器遍历向量来提高性能:

#include <iostream>
#include <vector>
#include <string>
#include <chrono>

int main() {

    std::vector<std::string> array = { "a", "b", "c", "d", "e" };

    int current;
    int next;

    for (current = 0; current < array.size(); ++current)
    {
        for (next = current + 1; next < array.size(); ++next)
        {
            std::cout << array[current] << array[next] << "\n";
        }
    }

    return 0;
}

【讨论】:

  • 为什么你认为 [] 更快?
【解决方案2】:

好吧,如果您只想要所有组合的排列,那真的很简单,因为每个组合中只有两个项目。所以只需反转打印 - 比如:

  std::vector<std::string> array = {"a", "b", "c", "d", "e"};
  std::vector<std::string>::iterator it = array.begin();
  for ( ; it < array.end(); it++ ) {
    for (std::vector<std::string>::iterator it_next = it+1 ; it_next < array.end(); it_next++ ) {
        std::cout << *it << *it_next << "\n";

        // Print the permutation - simply swap the order
        std::cout << *it_next << *it << "\n";
    }
  }
}

我误解了 OP 想要什么的旧答案

另外,有没有办法找到排列?

是的,可以通过多种方式完成,但 std::next_permutation 似乎很合适。

#include <algorithm>
#include <string>
#include <iostream>
#include <vector> 

// Print the vector
void pv(const std::vector<std::string>& v)
{
    for (const auto& s : v)
    {
        std::cout << s << " ";
    }
    std::cout << std::endl;
}

int main()
{
    std::vector<std::string> array = {"a", "b", "c"};
    std::sort(array.begin(), array.end());
    do 
    {
        pv(array);
    } while(std::next_permutation(array.begin(), array.end()));
}

输出:

a b c 
a c b 
b a c 
b c a 
c a b 
c b a 

【讨论】:

  • 谢谢.. 我会看看 std::next_permutation。但我的问题是找到 n 个元素中的两个的排列。在您的回答中,它是数组的所有元素。
  • @infoclogged 好的,看来我误解了你的问题。所以我试图弄清楚你想要什么。 ab 的排列将是 ba - 这就是你要找的吗?每个组合都完成了吗?
  • @infoclogged - 你想要的输出很简单:ab ba ac ca ad da ae ea bc cb bd db be eb cd dc ce ec de ed ?
  • 抱歉,回复晚了。是的,确切地说,这也是排列的定义(顺序很重要,即 ab 与 ba 不同)。因此,组合将返回 10 个集合,排列将返回 20 (5!/3!)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2019-12-06
  • 2012-10-15
  • 2018-08-01
  • 1970-01-01
相关资源
最近更新 更多