我的代码有一个名为 INPUTS 的列表,其中包含动态数量的列表,我们称它们为 A、B、C、.. N。这些列表包含动态数量的事件
我想调用每个事件组合的函数。举例说明:
INPUTS: A(0,1,2), B(0,1), C(0,1,2,3)
我需要为每个组合多次调用我的函数(输入计数是动态的,在这个例子中它是三个参数,但它可以或多或少)
function(A[0],B[0],C[0])
function(A[0],B[1],C[0])
function(A[0],B[0],C[1])
function(A[0],B[1],C[1])
function(A[0],B[0],C[2])
function(A[0],B[1],C[2])
function(A[0],B[0],C[3])
function(A[0],B[1],C[3])
function(A[1],B[0],C[0])
function(A[1],B[1],C[0])
function(A[1],B[0],C[1])
function(A[1],B[1],C[1])
function(A[1],B[0],C[2])
function(A[1],B[1],C[2])
function(A[1],B[0],C[3])
function(A[1],B[1],C[3])
function(A[2],B[0],C[0])
function(A[2],B[1],C[0])
function(A[2],B[0],C[1])
function(A[2],B[1],C[1])
function(A[2],B[0],C[2])
function(A[2],B[1],C[2])
function(A[2],B[0],C[3])
function(A[2],B[1],C[3])
目前我想到的是: 到目前为止,我的方法是构建一个组合列表。元素组合本身是输入数组 A、B 和 C 的“索引”列表。对于我们的示例:
我的列表 iCOMBINATIONS 包含以下 iCOMBO 列表
(0,0,0)
(0,1,0)
(0,0,1)
(0,1,1)
(0,0,2)
(0,1,2)
(0,0,3)
(0,1,3)
(1,0,0)
(1,1,0)
(1,0,1)
(1,1,1)
(1,0,2)
(1,1,2)
(1,0,3)
(1,1,3)
(2,0,0)
(2,1,0)
(2,0,1)
(2,1,1)
(2,0,2)
(2,1,2)
(2,0,3)
(2,1,3)
然后我会这样做:
foreach( iCOMBO in iCOMBINATIONS)
{
foreach ( P in INPUTS )
{
COMBO.Clear()
foreach ( i in iCOMBO )
{
COMBO.Add( P[ iCOMBO[i] ] )
}
function( COMBO ) --- (instead of passing the events separately)
}
}
但我需要找到一种方法来为任何给定数量的输入及其事件构建列表 iCOMBINATIONS。有什么想法吗?
真的有比这更好的算法吗? 任何可以帮助我的伪代码都会很棒。
C#(或 VB)
谢谢
最佳答案
您可以使用数组来保存每个列表的索引。示例:
List<List<int>> lists = new List<List<int>> {
new List<int> { 0,1,2 },
new List<int> { 0,1 },
new List<int> { 0,1,2,3 }
};
int[] cnt = new int[lists.Count];
int index;
do {
Console.WriteLine(String.Join(",", cnt.Select((c,i) => lists[i][c].ToString()).ToArray()));
index = cnt.Length - 1;
do {
cnt[index] = (cnt[index] + 1) % lists[index].Count;
} while(cnt[index--] == 0 && index != -1);
} while (index != -1 || cnt[0] != 0);
关于c# - 动态组合算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2620152/