Looking at each combination in jagged array

前端 未结 2 1776
予麋鹿
予麋鹿 2020-12-02 02:39

What is the fastest way to loop through each possible combination of elements in a jagged array with an unknown number of rows, and an unknown number of columns in each row?

2条回答
  •  醉话见心
    2020-12-02 03:28

    This works pretty sweet:

    Func>, IEnumerable>> combine = null;
    combine = css =>
                from c in css.First()
                from cs in css.Skip(1).Any()
                    ? combine(css.Skip(1)) 
                    : new [] { Enumerable.Empty() }
                select new [] { c }.Concat(cs);
    

    If I turn the result of running your data into a string with this:

    var result =
        String.Join(
            ", ",
            combine(myArray)
                .Select(c => String.Join("", c)));
    

    ...then I get this result: ACE, ACF, ADE, ADF, BCE, BCF, BDE, BDF.

    This computes very fast, but it would be interesting to know what the real world input is to see if this is fast enough.

提交回复
热议问题