Different combinations of an array (C#)

后端 未结 2 1216
遇见更好的自我
遇见更好的自我 2020-12-22 15:31

how can we find out different combination of the elements of an array using c# code. are there any inbuilt library function for this.?

for eg: suppose an array has e

相关标签:
2条回答
  • 2020-12-22 16:01
    static void Main()
    {
        var cnk = comb(new [] {1,2,3},2);
        foreach ( var c in cnk)
        {
        }
    }
    
    public static IEnumerable<int[]> comb(int[] a, int k)
    {
        if (a == null || a.Length == 0 || k < 1 || k > a.Length)
            yield break;
    
        int n = a.Length;   
        // 1
        if ( k == 1)
            for ( int i = 0; i < n; i++)
            {   
                yield return new int[] {a[i]};
            }
        else
            {
                // k
                for ( int i = 0; i < n - k + 1; i++)
                {
                    var res = new int[k];
                        for (int t = i, c = 0; t < i + k - 1; t++, c++)                 
                            res[c] = a[t];              
                    for (int j = i + k - 1; j < n; j++)
                    {                                                               
                        res[k-1] = a[j];                    
                        yield return res;
                    }
                }
            }
    }
    

    You should take the algorithm from here, my answer doesn't solve your problem Algorithm to return all combinations of k elements from n

    0 讨论(0)
  • 2020-12-22 16:05

    Seemed logic is not absolutely correct as:

    var cnk = comb(new[] { 1, 2, 3, 4 }, 3);
    

    This gives 3 variants, but as a matter of fact it is 4:

    1 2 3
    1 2 4
    1 3 4
    2 3 4
    

    I guess comb is better to be implemented in recursive way.

    0 讨论(0)
提交回复
热议问题