Algorithm for dynamic combinations

Posted by sOltan on Stack Overflow See other posts from Stack Overflow or by sOltan
Published on 2010-04-12T06:04:35Z Indexed on 2010/04/12 6:13 UTC
Read the original article Hit count: 1218

My code has a list called INPUTS, that contains a dynamic number of lists, let's call them A, B, C, .. N. These lists contain a dynamic number of Events

I would like to call a function with each combination of Events. To illustrate with an example:

INPUTS: A(0,1,2), B(0,1), C(0,1,2,3)

I need to call my function this many times for each combination (the input count is dynamic, in this example it is three parameter, but it can be more or less)

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])

This is what I have thought of so far: My approach so far is to build a list of combinations. The element combination is itself a list of "index" to the input arrays A, B and C. For our example:

my list iCOMBINATIONS contains the following iCOMBO lists

(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)

Then I would do this:

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)
      }
}

But I need to find a way to build the list iCOMBINATIONS for any given number of INPUTS and their events. Any ideas?

Is there actually a better algorithm than this? any pseudo code to help me with will be great.

C# (or VB)

Thank You

© Stack Overflow or respective owner

Related posts about c#

Related posts about algorithm