/*-*-mode:c-*-
***************************************************************************
CSN381: Project 2, problem 2
http://homepage.mac.com/hteric/Project2.pdf
***************************************************************************
File : permutation.c
Author : Jeremy Russell
Date : September 23, 2002
Description : Project 2, 2
***************************************************************************/
#include <stdio.h>
#define SIZE 5
void perm ( int, char *, int, char *, int *);
int main ( void )
{
char letters[SIZE] = {'a', 'b', 'c', 'd', 'e'};
char empty[SIZE];
int total = 0;
perm (SIZE, letters, 0, empty, &total);
printf ("Total number of permutations: %d.\n", total);
return 0;
}
/***************************************************************************
Function : perm
Author : Jeremy Russell
Date : September 23, 2002
Description : Works through the permutaion of an array. When the last
of the charcters is reached, then the permutation is printed.
Arguments : int lenLeft, char *left, int lenUsed, char *used, int *totalPerm
Returns : void
Notes : None
See Also : None
***************************************************************************/
void perm(int lenLeft, char *left, int lenUsed, char *used, int *totalPerm)
{
int i, j, k, n, m;
char tmpLeft[SIZE];
char tmpUsed[SIZE];
if ( lenLeft == 1 )
{
for ( i = 0; i < lenUsed; i++)
{
printf ("%c", used[i]);
}
printf ("%c\n", left[0]);
*totalPerm = *totalPerm + 1;
}
else
{
//Recurse the letters which are left, trying them out
// in the current position, until there is only one letter left.
// When one letter remains, print the array of letters.
for ( i = 0; i < lenLeft; i++)
{
m = 0;
// Create a new used array that has all the letters
// that have already been used.
for ( n = 0; n < lenUsed; n++)
{
tmpUsed[n] = used[n];
m++;
}
tmpUsed[m] = left[i];
m++;
// Create a tmp array that contains all the letters
//which have not been used.
k = 0;
for (j = 0; j < lenLeft; j++ )
{
if (left[j] != left[i])
{
tmpLeft[k] = left[j];
k++;
}
}
// Recurse the permutation.
perm ( k, tmpLeft, m, tmpUsed, totalPerm);
}
}
}