Code:
e.g.
{ 1, 2, 3 }.Combine(2) = {{ 1, 2 }, { 1, 3 }, { 2, 3 }}
{ 1, 2 }.Combine(2, true) = {{ 1, 1 }, { 1, 2 }, { 2, 2 }}
{ 1, 2, 3, 4 }.Combine(3) = {{ 1, 2, 3 }, { 1, 2, 4 }, { 2, 3, 4 }}
public static IEnumerable<IEnumerable<T>> Combine<T>(this IEnumerable<T> list, int k = 2, bool repetition = false) { for (int i = 0; i < list.Count(); i++) { T cur = list.Skip(i).First(); if (k == 1) { yield return cur.Yield(); } else { foreach (var res in list.Skip(i + (repetition ? 0 : 1)).Combine(k - 1, repetition)) { yield return res.Prepend(cur); } } } }
No comments:
Post a Comment