/* IO(1) */

matrix permutations( vector _v)
{
/* generate permutation matrix of vector elements */

  matrix c, cnext;
  vector vnext;
  int i, R, R2;
  int m;

  if( narg != 1) {
    print( "permutations: narg must be 1");
    return 0;
  }

  m = cols(_v);

  if( m == 1)	/* 1 permutation is just _v itself */
    return _v;

  R2 = prod(1:m-1);
  R = m * R2;	/* number of permutations == rows(c) */

  c = zeros( R, m);
  vnext = _v;
  i = 1;

  while( i <= R) {
    cnext = permutations( vnext(2:m));
    c(i:i+R2-1) = [reshape(vnext(1),R2,1), cnext];
    vnext = [vnext(2:m) vnext(1)];
    i += R2;
  }

  return c;
}
