user722591
user722591

Reputation: 43

To find combination of a list

i'm implementing Apriori algorithm. and i need to calculate the combination of a list for example i have a list containing ABC DEF GHI JKL and its out put should be like this ABCDEF ABCGHI ABCJKL

plz tell me that hw i can get the output like this.....

Upvotes: 3

Views: 174

Answers (1)

sehe
sehe

Reputation: 392929

It is called the cartesian product

Simple approach

var inputs = new [] { "ABC", "DEF", "GHI", "JKL", "MNO" };
var combi = from first in inputs
            from second in inputs
            select first+second;

Flexible approach (published by Eric Lippert)

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
{ 
  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
  return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) =>  
      from accseq in accumulator  
      from item in sequence  
      select accseq.Concat(new[] {item}));                
}

Use it like

var combi = new [] { inputs, inputs }.CartesianProduct();

The power comes from being able to do

var combi = new [] { inputs, inputs, somethingelse, inputs }.CartesianProduct();

just as easily

Upvotes: 6

Related Questions