Hi folks,

While trying to generate all combinations of length X in an array,
I came across the question on stackoverflow. [1]

Theres a couple good answers there, but one that caught my eye shows a C# code snippet that is quite nice and short:

public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
  return k == 0 ? new[] { new T[0] } :
    elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] {e}).Concat(c)));
}


I spent a couple hours trying to translate this to D, but couldnt get my head around the SelectMany statement. I think it's analogous to std.algorithm.map, but it seems quite difficult to mimic the behaviour using map.

Anyone with more knowledge and/or skills like to have a crack?

Thanks!

[1] http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n

Reply via email to