我有一个数字序列要生成,我想用某种算法生成它(迭代或递归,无所谓)。在
上下文化:这些数字是对列表列表进行迭代的索引。我需要做一个排列(组合,我不太清楚),但我需要生成列表中所有位置的所有组合。在
我要得到的序列和输出是:
1 1
2 1
3 1
4 1
5 1
1 2
2 1
3 1
4 1
5 1
1 3
2 1
3 1
4 1
5 1
1 4
2 1
3 1
4 1
5 1
1 5
2 1
3 1
4 1
5 1
1 1
2 2
3 1
4 1
5 1
1 2
2 2
3 1
4 1
5 1
1 3
2 2
3 1
4 1
5 1
1 4
2 2
3 1
4 1
5 1
1 5
2 2
3 1
4 1
5 1
1 1
2 3
3 1
4 1
5 1
1 2
2 3
3 1
4 1
5 1
1 3
2 3
3 1
4 1
5 1
1 4
2 3
3 1
4 1
5 1
1 5
2 3
3 1
4 1
5 1
1 1
2 4
3 1
4 1
5 1
等等。。。最后一种状态是:
^{pr2}$注意,在每个换行符处都是一个迭代或递归的步骤。算法必须是泛型的。我写的这段代码可以帮上忙,但这不是我想要的。:(
List<List<int>> lstDays = new List<List<int>>
{
new List<int>{1,2,3,4,5}, //day 18
new List<int>{1,2,3,4,5}, //day 19
new List<int>{1,2,3,4,5}, //day 22
new List<int>{1,2,3,4,5}, //day 23
new List<int>{1,2,3,4,5}, //day 24
};
for(int i=0;i<lstDays.Count;i++)
{
for(int j=0;j<lstDays[i].Count;j++)
{
for(int k=0;k<lstDays.Count;k++)
{
Console.Write(k+1);
//Console.Write(j+1);
Console.Write('\n');
}
Console.Write('\n');
}
}
我希望你能帮助我!(:
你可以这样做:
第二个数字的序列“创造性地”存储在名为
second
的数组中。do
/while
循环“递增”这个数组,就好像它是一个以5个独立数字形式存储的基数5。在这是一个demo on ideone。在
根据尊敬的埃里克·利珀特(Eric Lippert)的以下评论,对OPs的初衷进行了编辑:
OutputSequence(5);
将给出操作最初请求的输出。在旧答案
你要找的是一个Cartesian Product。林肯是你的朋友:
^{pr2}$编辑:为了好玩,这里有一个方法来做N元笛卡尔积。在
现在,您可以通过以下方式获得以前的体验:
我相信有一种比一直创建新阵列更有效的方法,但我只是很快就搞定了:)
这里有一个更丰富的答案:Generating all Possible Combinations
编辑2:很明显,原始链接是来自那个SO帖子的答案的来源。我直到现在才读完。在
相关问题 更多 >
编程相关推荐