c# - 动态组合算法

标签 c# algorithm combinatorics combinations

我的代码有一个名为 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/

相关文章:

c# - 将 VBA 转换为 .NET 语言

algorithm - 我应该采取什么步骤来识别这个算法

php - PHP 中的数组组合

python - 如何在 Python 中生成所有不同 3x3 拉丁方的列表

python - 如何创建一个迭代列表,其中一些变量是独立的,一些是相关的?

c# - App.config 中的 connectionStrings configSource 不起作用

c# - 如何将参数传递给 ICommand?

c# - Properties.Settings.Default 是否有非默认替代方案?

algorithm - 比较两个数据结构的相似性

根据另一个问题的标题查找相似问题的算法?