Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

generate possible combonations

Status
Not open for further replies.

galger

MIS
Jan 16, 2002
79
US
There is probably a unix script out there like this..

Need to generate possible combonations of a paticular list.

example:
~
sally
bill
greg
jim
~

sally bill greg jim
jim greg bill sally
and so on....


 
Hi:

I'm reading the elements into an array and RANDOMly printing out the elements.

Here's a place to start, but there are some limitations:

1) I'm hard coding the elements. You can change it to read them in from a file.

2) The elements repeat so I leave it to you to change that if it's unacceptable.

3) I'm hard coding 4 iterations.

Code:
#!/bin/ksh

function in_range_random_number
{
# Create a pseudo-random number less than or equal
# to the $UPPER_LIMIT value which is passwd as command
# line argument $1.

echo "$(($RANDOM % $1 + 1))"

}

NUMSTR=4 # number of strings
X=0
for STR in sally bill greg jim
do
   ((X+=1)) # Increment the counter by 1
   MYSTR[$X]=$STR
done
UPPER_LIMIT=$X  # Random Number Upper Limit

#
# Produce the "for" loop list of elements that represent
# the number of strings
FOR_COUNT=$(
X=0
while ((X < NUMSTR))
do
   ((X+=1))
   echo "$X "
done
)

# Build the string using random numbers to grab array
# elements from the MYSTR array.
for i in 1 2 3 4
do
   NEWSTR=""
   for i in $FOR_COUNT
   do
      NEWSTR="${NEWSTR} ${MYSTR[$(in_range_random_number $UPPER_LIMIT)]}"
   done
   echo $NEWSTR
done
 
here's a the awk code ['stolen' and ported from Permutations ] prints all possible permutations of an array of items. The array is hard-coded as '1 2 3' - but can be read in from stdin/file.

nawk -f permutations.awk < /dev/null

Code:
BEGIN {
  strN=split("1 2 3", str, " ")
  permute(str, 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;
    }
  }
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top