C# advanced permutation scenario

后端 未结 4 933
北恋
北恋 2021-01-20 20:55

I am trying to figure how how to find all the combinations given the following information:

I start with a JSON dataset:

var choices = { 1: {\'Q\': 1         


        
4条回答
  •  时光说笑
    2021-01-20 22:00

    What you are looking for is the Cartesian Product of 10 arrays (10-ary Cartesian product as I think it is more properly called). Eric Lippert wrote a good (and quite advanced) article on doing this for an arbtirary number of arrays here: http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/

    The upshot of it is that I think the following function will do what you want:

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

    The input in your case is an array of your 10 arrays. The output would be an ienumerable that would return at each step an ienumerable of ten items. You would basically iterate over the output of that function to get all your possible permutations.

提交回复
热议问题