//------------------------------------------------------------------- // permlist.cpp // // This program displays a list of all the permutations of the // first n uppercase letters of the alphabet where the value // for n is supplied by the user as a command-line argument. // // to compile: g++ permlist.cpp -o permlist // to execute: ./permlist // // programmer: ALLAN CRUSE // written on: 01 MAY 2011 //------------------------------------------------------------------- #include // for printf(), fprintf() #include // for atoi(), exit() #define MAXSIZE 26 // number of uppercase letters char list[ MAXSIZE ]; // array of uppercase letters int n = 3; // order for the permutations void permute( char list[], int k, int m ) { if ( k < m ) for (int i = k; i < m; i++) { // swap a[i] with a[m-1] char temp = list[ i ]; list[ i ] = list[ m-1 ]; list[ m-1 ] = temp; permute( list, k, m-1 ); // swap a[m-1] with a[i] temp = list[ i ]; list[ i ] = list[ m-1 ]; list[ m-1 ] = temp; } else { for (int i = 0; i < n; i++) printf( "%c", list[ i ] ); printf( "\n" ); } } int main(int argc, char **argv ) { // get command-line argument if ( argc > 1 ) n = atoi( argv[ 1 ] ); if (( n < 1 )||( n > MAXSIZE )) { fprintf( stderr, "Invalid argument\n" ); exit(1); } // initialize the character-list for (int i = 0; i < MAXSIZE; i++) list[ i ] = (char)('A' + i); // use recursion to show all permulations on first n letters printf( "\n" ); permute( list, 0, n ); printf( "\n" ); }