#include #include using namespace std; class permuter { protected: int pos[27]; int inuse[27]; int N; public: int perm[27]; permuter(int n); bool next(); }; permuter::permuter(int n) { N = n; for (int i = 0; i < N; i += 1) { pos[i] = 1; inuse[i] = 0; } pos[n] = 0; } bool permuter::next() { int n = N; while (n > 0) { pos[n] += 1; if (pos[n] <= N + 1 - n) break; pos[n] = 1; n -= 1; } if (n == 0) return false; for (int i = 1; i <= N; i += 1) inuse[i] = 0; for (int i = 1; i <= N; i += 1) { int w = pos[i]; for (int j = 1; j <= N; j += 1) { if (! inuse[j]) { w -= 1; if (w == 0) { perm[i] = j; inuse[j] = 1; } } } } return true; } int main(int argc, char * argv[]) { if (argc != 2) { cerr << "Put the number of items on the command line\n"; exit(1); } const int n = atol(argv[1]); if (n < 0 || n > 26) { cerr << "Number of items limited to range 0...26\n"; exit(1); } const string vars = "-abcdefghijklmnopqrstuvwxyz"; permuter P(n); while (P.next()) { for (int i = 1; i <= n; i += 1) cout << " " << vars[P.perm[i]]; cout << "\n"; } }