Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian products with n number of list

I am having

List<List<string>> AllSimilarWordsLists { get; set; }

I want to generate string from these words such that no string is duplicate and Here duplicate means each and every string must contain unique words

e.g if once generated 'How are you' then 'are you how' should not be considered in result'.

I can have any number of list

e.g

List1   List2   List3   List4   List5
word11  word21  word21  word21  word51
word12  word22  word22  word22  word52
word13  word23  word23  word23  word53
word14  word24  word24  word24  word54
word15  word25  word25  word25  word55

These list are going to be added in AllSimilarWordsLists. I want to generate list of string using cartesian products . Have found this but this solution is having fix number of lists, Anybody having ideas.

like image 562
Nitin Varpe Avatar asked Jan 10 '23 22:01

Nitin Varpe


1 Answers

Unfortunately I don't remember where I found it

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>
    (this IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct =
      new[] { Enumerable.Empty<T>() };
    IEnumerable<IEnumerable<T>> result = emptyProduct;
    foreach (IEnumerable<T> sequence in sequences)
    {
        result = from accseq in result from item in sequence select accseq.Concat(new[] {item});
    }
    return result;
}
like image 68
Vladmir Avatar answered Jan 21 '23 02:01

Vladmir