Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To find combination of a list

Tags:

c#

asp.net

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.....

like image 746
user722591 Avatar asked Nov 21 '25 16:11

user722591


1 Answers

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

like image 114
sehe Avatar answered Nov 24 '25 07:11

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!