任意数量的嵌套循环?

时间:2010-08-21 07:49:18

标签: c++ nested metaprogramming permutation

我正在寻找任意数量的列表(例如[2,1,4 ...],[8,3,...],...)并从每个列表中选择数字以便生成所有排列。 E.g:

[2,8,...], [2,3,...], [1,8,...], [1,3,......], [4,8,...], [4,3,...],    ...

使用嵌套的for循环很容易实现,但是因为我想接受任意数量的列表,所以for循环似乎必须是硬编码的。每个列表一个。此外,由于我的程序可能会产生数万个排列,我想一次生成一个单独的排列(而不是一次性计算它们并将结果存储到向量中)。有没有办法以编程方式完成此操作?

由于在编译时知道列表的数量,我想也许我可以使用基于模板的元编程。然而,这看起来很笨拙,也不符合“一次一个”的要求。有什么建议吗?

7 个答案:

答案 0 :(得分:6)

你可以使用计数的基本原理,比如递增最后一位数直到达到最大值,然后递增倒数第二位,依此类推,就像倒计时一样 这是一个示例代码,假设可能存在差异列表的差异。

#include <iostream>
using namespace std;
int main() {
    int n;
    cin>>n;
    int a[n], len[n],i,j;
    for(i = 0 ; i < n ; i++)
    {
        cin>>len[i];
        a[i]=0;
    }
    while(1)
    {
        for(i = 0 ; i< n;i++)
            cout<<a[i]<<" ";
        cout<<endl;
        for(j = n-1 ; j>=0 ; j--)
        {
            if(++a[j]<=len[j])
                break;
            else
                a[j]=0;
        }
        if(j<0)
            break;
    }    
    return 0;
}

尝试使用4 1 1 1 1运行代码,它将提供0和1的所有4位数字排列。

0 0 0 0 
0 0 0 1 
0 0 1 0 
0 0 1 1 
0 1 0 0 
0 1 0 1 
0 1 1 0 
0 1 1 1 
1 0 0 0 
1 0 0 1 
1 0 1 0 
1 0 1 1 
1 1 0 0 
1 1 0 1 
1 1 1 0 
1 1 1 1 

您可以使用2d数组来获取nos的组合。

答案 1 :(得分:3)

递归方式......

void Recurse(const vector<vector<int>>& v, 
             size_t listToTwiddle, 
             vector<int>& currentPermutation)
{
    // terminate recursion
    if (listToTwiddle == v.size())
    {
        for(auto i = currentPermutation.cbegin(); i != currentPermutation.cend(); ++i)
        {
            cout << *i << " ";
        }
        cout << endl;
        return;
    }

    for(size_t i = 0; i < v[listToTwiddle].size(); ++i)
    {
        // pick a number from the current list
        currentPermutation.push_back(v[listToTwiddle][i]);

        // get all permutations having fixed this number
        Recurse(v, listToTwiddle + 1, currentPermutation);

        // restore back to original state
        currentPermutation.pop_back();
    }
}

void Do(const vector<vector<int>>& v)
{
    vector<int> permutation;
    Recurse(v, 0, permutation);
}

答案 2 :(得分:2)

STL没有现成的功能,但您可以通过修改next_permutation的某些部分来编写自己的实现。

问题类似于实现二进制数字加法器。增加array[0]。如果array[0]的新值溢出(意味着其值大于您拥有的列表数),则将array[0]设置为零并增加array[1]。等等。

答案 3 :(得分:2)

好玩。

你似乎希望它实际上是一种迭代器,它会遍历给定的范围,并且每一步都会给你一个排列。

通常可以在没有元编程的情况下编写,特别是因为自C ++ 0x以来仅支持可变参数模板。尽管如此,这是一个非常有趣的挑战。

我们这里的第一个助手将是小tuple级。我们还需要一些元模板编程技巧来将一个元组转换为另一个元组,但我会让它作为练习让读者编写必要的元模板函数和执行转换的实际函数(读到:今天下午对我来说太热了)。

这是让你前进的事情。

template <class... Containers>
class permutation_iterator
{
public:
  // tuple of values
  typedef typename extract_value<Containers...>::type value_type;

  // tuple of references, might be const references
  typedef typename extract_reference<Containers...>::type reference;

  // tuple of pointers, might be const pointers
  typedef typename extract_pointer<Containers...>::type pointer;

  permutation_iterator(Containers&... containers) { /*extract begin and end*/ }

  permutation_iterator& operator++()
  {
    this->increment<sizeof...(Containers)-1>();
    return *this;
  }

private:
  typedef typename extract_iterator<Containers...>::type iterator_tuple;

  template <size_t N>
  typename std::enable_if_c<N < sizeof...(Containers) && N > 0>::type
  increment()
  {
    assert(mCurrent.at<N>() != mEnd.at<N>());
    ++mCurrent.at<N>();
    if (mCurrent.at<N>() == mEnd.at<N>())
    {
      mCurrent.at<N>() = mBegin.at<N>();
      this->increment<N-1>();
    }
  }

  template <size_t N>
  typename std::enable_if_c<N == 0>::type increment()
  {
    assert(mCurrent.at<0>() != mEnd.at<0>());
    ++mCurrent.at<0>();
  }

  iterator_tuple mBegin;
  iterator_tuple mEnd;
  iterator_tuple mCurrent;
};

如果你不知道怎么去元,那么更简单的方法是递归,然后要求用户通过at方法指定她希望访问哪个容器N为用于指示容器索引的参数。

答案 4 :(得分:1)

因此,经过进一步研究,我发现我正在尝试做的事情被称为笛卡尔积。我最终使用了this代码的略微修改版本。只是想我会更新这个以防万一其他人偶然发现这个问题寻找相同的答案。

答案 5 :(得分:0)

使用递归你可能会“自己”使用当前位置,剩余列表等等。这有可能溢出,但通常可以将递归函数转换为非递归函数(就像使用for循环一样),尽管大部分优雅都会消失。

答案 6 :(得分:0)

非递归方式:

#include <vector>
#include <iostream>

// class to loop over space
// no recursion is used
template <class T>
class NLoop{

public:

    // typedefs for readability
    typedef std::vector<T> Dimension;
    typedef std::vector< Dimension > Space;
    typedef std::vector< typename Dimension::iterator > Point;

    // the loop over space and the function-pointer to call at each point
    static void loop(Space space, void (*pCall)(const Point&))
    {

        // get first point in N-dimensional space
        Point current;
        for ( typename Space::iterator dims_it = space.begin() ; dims_it!=space.end() ; ++dims_it )
        {
            current.push_back( (*dims_it).begin() );
        }

        bool run = true;
        while ( run )
        {

            // call the function pointer for current point
            (*pCall)(current);

            // go to next point in space
            typename Space::iterator dims_it = space.begin();
            typename Point::iterator cur_it = current.begin();
            for (  ; dims_it!=space.end() ; ++dims_it, ++cur_it )
            {
                // check if next in dimension is at the end
                if ( ++(*cur_it) == (*dims_it).end() )
                {
                    // check if we have finished whole space
                    if ( dims_it == space.end() - 1 )
                    {
                        // stop running now
                        run = false;
                        break;
                    }
                    // reset this dimension to begin
                    // and go to next dimension
                    *cur_it = (*dims_it).begin();
                }
                else
                {
                    // next point is okay
                    break;
                }
            }

        }
    }
};


// make typedef for readability
// this will be a loop with only int-values in space
typedef NLoop<int> INloop;

// function to be called for each point in space
// do here what you got to do
void call(const INloop::Point &c)
{
    for ( INloop::Point::const_iterator it = c.begin() ; it!=c.end() ; ++it)
    {
        std::cout << *(*it) << " ";
    }
    std::cout << std::endl;
}

int main()
{

    // fill dimension
    INloop::Dimension d;
    d.push_back(1);
    d.push_back(2);
    d.push_back(3);

    // fill space with dimensions
    INloop::Space s;
    s.push_back(d);
    s.push_back(d);
    s.push_back(d);

    // loop over filled 'space' and call 'call'
    INloop::loop(s,call);

    return 0;

}