unique numbers $1 - n$
combinations (sets) of size $k$
$k < n$
do not re-use an $n$ in a set [1, 1, 1] is not valid
How to generate all unique sets of size $k$?
[1,2,3] = [3,2,1] order does not matter
the number of sets will be ${\binom{n}{k}}$
input
$n = 4, k = 2$
output
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
I have found that is often called n chose k
hard coded it looks like
for (i = i; i <= n - 1; i++)
for (j = i + 1; j <= n - 1; j++)
I tried coding the first solution from Yuval Filmus but it does not work for me
It returns [1,2], [1,2]
Had to adjust for 0 based arrays
public static void Combinations(int n, int k)
{
bool[] A = new bool[n];
int[] B = Enumerable.Range(1, k).ToArray();
Generate(1, A, B, k, n);
}
public static void Generate(int l, bool[] A, int[] B, int k, int n)
{
Debug.WriteLine(string.Join(", ", B));
if (l == k + 1)
{
Debug.WriteLine("l == k + 1");
return;
}
for (int i = 0; i < n; i++)
{
if (!A[i])
{
A[i] = true;
B[l - 1] = i + 1;
Generate(l + 1, A, B, k, n);
A[i] = false;
}
}
}