Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google site




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #2 (permalink)  
Old 03-19-2009
vgersh99's Avatar
vgersh99 vgersh99 is offline Forum Staff  
Moderator
 

Join Date: Feb 2005
Location: Boston, MA
Posts: 5,189
This's called permutations.
Here's a starting point - you can expand on this to read from a file:

nawk -v str='1 2 3 4 5 6 7 8 9' -f perm.awk

perm.awk:

Code:
BEGIN {
  str = ( str != "") ? str : "1 2 3"
  strN=split(str, arr, " ")
  permute(arr, 1, strN)
}

function printV(v, size,   i)
{
    for (i = 1; i <= size; i++) {
      printf("%4d", v[i] );
    }
    printf("\n");
}


function permute(v, start, n,    i,tmp)
{
  if (start == n) {
    printV(v, n);
  }
  else {
    for (i = start; i <= n; i++) {
      tmp = v[i];

      v[i] = v[start];
      v[start] = tmp;
      permute(v, start+1, n);
      v[start] = v[i];
      v[i] = tmp;
    }
  }
}