c# - How to make combination based on limit provided? -


i have array under

var x = new int[] { 1,2,3 }; 

and given limit

int limit=2; 

i have find combination

1+2 = 3 1+3 = 4 2+3 = 5. 

if array say

var x = new int[] { 1,2,3,4,5,6}; 

and given limit

int limit=3; 

the combination should be

1+2+3 = 6  1+2+4 = 7  1+2+5 = 8  1+2+6 = 9  2+3+4  = 9  2+3+5 = 10  2+3+6 = 11 ........... ............ 

and on

how so?

my bad attampt

var x = new int[] {1,2,3};         int limit = 2;          var m = a1 in x                 a2 in x                                 select new                     {                         p1 = a1 ,                         p2 = a2,                                              p3 = a1+a2                     }; 

a solution without use of external library:

public static ienumerable<ienumerable<t>> combinations<t>(ienumerable<t> elements, int k) {   return k == 0 ? new[] { new t[0] } :     elements.selectmany((e, i) =>       combinations(elements.skip(i + 1),k - 1).select(c => (new[] {e}).concat(c))); }  public static void main() {     var x = new int[] { 1, 2, 3, 4, 5, 6 };     var limit = 3;     ienumerable<ienumerable<int>> result = combinations(x, limit);       foreach(var combi in result)         console.writeline(string.join("+", combi.select(a=>a.tostring()).toarray()) + "=" + combi.sum());     console.writeline("total: " + result.sum(c => c.sum())); // 201 } 

edit : combinations:

public static ienumerable<ienumerable<t>> allcombinations<t>(ienumerable<t> elements) {     int length = elements.count();     for(int k = 1; k<=length; k++){         var comb = combinations(elements, k);         foreach (ienumerable<t> c in comb)             yield return c;     } } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -