Obtaining combinations of k elements from n in C#
I needed an algorithm that could return all combinations of k number of elements within a finite set of n elements. Furthermore I wanted the algorithm to work in a non-recursive (iterative) way in C#. Step forward StackOverflow, specifically this answer given by Juan Antonio Cano I've taken his code and just made one or two modifications, as suggested by ReSharper . Full code listing for the console app as shown: Program.cs [code language="csharp"] using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Techniques { public static class Program { private static bool NextCombination(IList<int> num, int n, int k) { bool finished; var changed = finished = false; if (k <= 0) return false; for (var i = k - 1; !finished && !changed; i--) { if (num[i] < n - 1 - (k - 1) + i) { num[i]++; ...