Faster alternative to nested loops?

后端 未结 12 1469
栀梦
栀梦 2020-12-12 18:35

I have a need to create a list of combinations of numbers. The numbers are quite small so I can use byte rather than int. However it requires many

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 19:28

    var numbers = new[] { 2, 3, 4, 3, 4, 3, 3, 4, 2, 4, 4, 3, 4 };
    var result = (numbers.Select(i => Enumerable.Range(0, i))).CartesianProduct();
    

    Using the extension method at http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/

    public static IEnumerable> CartesianProduct(this IEnumerable> sequences)
    {
        // base case: 
        IEnumerable> result =
            new[] { Enumerable.Empty() };
        foreach (var sequence in sequences)
        {
            // don't close over the loop variable (fixed in C# 5 BTW)
            var s = sequence;
            // recursive case: use SelectMany to build 
            // the new product out of the old one 
            result =
                from seq in result
                from item in s
                select seq.Concat(new[] { item });
        }
        return result;
    }
    

提交回复
热议问题