任意数量的嵌套循环? [英] Arbitrary number of nested-loops?

查看:167
本文介绍了任意数量的嵌套循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要获取任意数量的列表(例如[2,1,4 ...],[8,3,...],...),并从每个列表中挑选数字,以生成所有排列。例如:

I'm looking to take an arbitrary number of lists (e.g. [2, 1, 4 . . .], [8, 3, ...], . . .) and pick numbers from each list in order to generate all permutations. E.g.:

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

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

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

This is easily accomplished using nested for-loops, but since I'd like to it accept an arbitrary number of lists it seems that the for-loops would have to be hard coded. One for each list. Also, as my program will likely generate many tens of thousands of permutations, I'l like to generate a single permutation at a time (instead of computing them all in one go and storing the result to a vector). Is there a way to accomplish this programatically?

由于列表的数量在编译时是已知的,我想我也许可以使用基于模板的元编程。然而,这似乎笨拙,也不符合一次一个的要求。任何建议?

Since the number of lists is know at compile time, I thought maybe I could use template based meta-programming. However that seems clumsy and also doesn't meet the "one at a time" requirement. Any suggestions?

推荐答案

您可以使用计数的基本原理,如增加最后一位数字,直到达到其最大值,第二个最后一个等等,如倒计时
这里是一个示例代码,假设可能有差异列表的差异长度。

You can use fundamental principal of counting, like incrementing the last digit till it reaches its max value, then increment the second last one and so on, like a countdown does Here is a sample code, assuming there might be diff length of diff lists.

#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个数字排列。

Try to run the code with 4 1 1 1 1 and it will give all 4 digit permutations of 0 and 1.

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。

You can use 2d arrays for getting combinations of nos.

这篇关于任意数量的嵌套循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆