ernie.WPI.EDU> cat permute.C // #define DEBUG // comment out this line when the code is working // file permute.C, cs2223, D97/98 // // 24Apr98 NW, First version // include #include "headers.h" // global value unsigned long int counter; // prototype void permute(int, int, int*); // calculate permutations of a vector // main int main () { while (1) { int n; cout << "enter a value of n: "; cin >> n; if (n <= 0) return 0; // exit criterion int *vect = new int[n]; // the vector for (int i = 0; i < n; i++) vect[i] = i; // fill the vector counter = 0; #ifdef DEBUG cout << setw(12) << "number" << " vect" << endl; #endif permute(0, n, vect); cout << "there were " << counter << " permutations" << endl << endl; } } // end main() void permute(int k, int n, int *vect) // calculate permutations of a vector { // n is the length of the vector, k is the position to begin permutations if (k >= n-1) { // permutation is complete counter++; #ifdef DEBUG cout << setw(12) << counter << " "; for (int i = 0; i < n; i++) cout << setw(3) << vect[i]; cout << endl; #endif return; } // end if(i) for (int i = k; i < n; i++) { int temp = vect[k]; vect[k] = vect[i]; vect[i] = temp; // swap permute(k+1, n, vect); // recursive call temp = vect[k]; vect[k] = vect[i]; vect[i] = temp; // swap back } } // end permute() // Copyright 1998 Norman Wittels ernie.WPI.EDU> g++ permute.C ernie.WPI.EDU> a.out enter a value of n: 3 there were 6 permutations enter a value of n: 8 there were 40320 permutations enter a value of n: 10 there were 3628800 permutations enter a value of n: -3 ernie.WPI.EDU>