How do I generate all permutations of k items selected from an array of n items?
However, I can't do this permutation using an auxiliary vector with 6 positions, so the algorithm is only varying the characters of [a..f], how can I make it vary all positions?
The code below generates all permutations of the first k items in the array. How do I expand it to generate all permutations of all selections of k items from n items?
#include <stdio.h>
#include <string.h>
#include <time.h>
void exchange(char v[], int i, int j)
{
int aux = v[i];
v[i] = v[j];
v[j] = aux;
}
void permutation(char v[], int inf, int sup)
{
if(inf == sup)
{
for(int i = 0; i <= sup; i++)
printf("%c ", v[i]);
printf("\n");
}
else
{
for(int i = inf; i <= sup; i++)
{
exchange(v, inf, i);
permutation(v, inf + 1, sup);
exchange(v, inf, i); // backtracking
}
}
}
int main()
{
char v[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int n = 6;
permutation(v, 0, n-1);
return 0;
}