How to generator all combinations (memory efficient algorithm)?

Just create an iterator method using yield return, like so:

   public class Combinations: IEnumerable<Combination> {
        public IEnumerator<T> GetEnumerator()
        {
            Combination currentCombination = Combination.FirstCombination(); 
            while (currentCombination.IsValid()) {
                yield return currentCombination;
                currentCombination = currentCombination.NextCombination(); // return invalid combo if currentCombination is the last possible combination
            }
        }
   }

Of course you still have to write the Combination class but that should be relatively straightforward. You should be able to generate the next combination from the current one. For example, say there are N elements in the list, you just have to increment a base-N number containing N digits and as you do that you will generate all combinations.

Leave a Comment