# List all possible combinations of k integers between 1...n (n choose k)

### Question

Out of no particular reason I decided to look for an algorithm that produces all possible choices of k integers between 1...n, where the order amongst the k integer doesn't matter (the n choose k thingy).

From the exact same reason, which is no reason at all, I also implemented it in C#. My question is:

Do you see any mistake in my algorithm or code? And, more importantly, can you suggest a better algorithm?

Please pay more attention to the algorithm than the code itself. It's not the prettiest code I've ever written, although do tell if you see an error.

EDIT: Alogirthm explained -

• We hold k indices.
• This creates k nested for loops, where loop i's index is indices[i].
• It simulates k for loops where indices[i+1] belongs to a loop nested within the loop of indices[i].
• indices[i] runs from indices[i - 1] + 1 to n - k + i + 1.

CODE:

``````public class AllPossibleCombination
{
int n, k;
int[] indices;
List<int[]> combinations = null;

public AllPossibleCombination(int n_, int k_)
{
if (n_ <= 0)
{
throw new ArgumentException("n_ must be in N+");
}
if (k_ <= 0)
{
throw new ArgumentException("k_ must be in N+");
}
if (k_ > n_)
{
throw new ArgumentException("k_ can be at most n_");
}

n = n_;
k = k_;
indices = new int[k];
indices = 1;
}

/// <summary>
/// Returns all possible k combination of 0..n-1
/// </summary>
/// <returns></returns>
public List<int[]> GetCombinations()
{
if (combinations == null)
{
combinations = new List<int[]>();
Iterate(0);
}
return combinations;
}

private void Iterate(int ii)
{
//
// Initialize
//
if (ii > 0)
{
indices[ii] = indices[ii - 1] + 1;
}

for (; indices[ii] <= (n - k + ii + 1); indices[ii]++)
{
if (ii < k - 1)
{
Iterate(ii + 1);
}
else
{
int[] combination = new int[k];
indices.CopyTo(combination, 0);
}
}
}
}
``````

I apologize for the long question, it might be fit for a blog post, but I do want the community's opinion here.

Thanks,
Asaf

1
11
4/13/2010 2:10:35 PM

In C++ given the following routine:

``````template <typename Iterator>
inline bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
/* Credits: Thomas Draper */
if ((first == last) || (first == k) || (last == k))
return false;
Iterator itr1 = first;
Iterator itr2 = last;
++itr1;
if (last == itr1)
return false;
itr1 = last;
--itr1;
itr1 = k;
--itr2;
while (first != itr1)
{
if (*--itr1 < *itr2)
{
Iterator j = k;
while (!(*itr1 < *j)) ++j;
std::iter_swap(itr1,j);
++itr1;
++j;
itr2 = k;
std::rotate(itr1,j,last);
while (last != j)
{
++j;
++itr2;
}
std::rotate(k,itr2,last);
return true;
}
}
std::rotate(first,k,last);
return false;
}
``````

You can then proceed to do the following:

``````std::string s = "123456789";
std::size_t k = 3;
do
{
std::cout << std::string(s.begin(),s.begin() + k) << std::endl;
}
while(next_combination(s.begin(),s.begin() + k,s.end()));
``````
9
11/25/2010 11:21:00 PM