Jul 27, 2008

generating permutations

Here's some code that I wrote to demonstrate a recursive algorithm for generating permutations of a vector. I deliberately wrote it in 'C', as I believe it is the lowest common denominator for computer science languages today.

The algorithm was listed in How to solve it: Modern Heuristics


typedef struct VEC_
{
int *x;
int sz;
} VEC;

// call: pos_perm(v,0,-1);
int pos_perm(VEC *v,int pos,int k)
{
k = k + 1;
v->x[pos] = k;
//printf("--pos=%d k=%d ",pos,k);
if ( k == v->sz )
{
print(v);
}
for (int q=0;q<v->sz;q++)
{
if ( v->x[q] == 0 ) pos_perm(v,q,k);
}
k = k - 1;
v->x[pos] = 0;
//printf("pos=%d k=%d\n",pos,k);
}

No comments: