Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Created August 5, 2016 11:30
Show Gist options
  • Save Swarchal/6f9faf75ba04c8d6ff44ae5f9a38b344 to your computer and use it in GitHub Desktop.
Save Swarchal/6f9faf75ba04c8d6ff44ae5f9a38b344 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <algorithm>
using namespace std;
//////////////////////////////////////////////////////////////////////////////
// Permute array of integers //
//////////////////////////////////////////////////////////////////////////////
// roll your own factorial function
int factorial(const int& x)
{
return (x == 1 || x == 0) ? 1 : factorial(x-1) * x;
}
void permute_array(const int& n)
{
// create an array from 1 to n
int my_ints[n];
for (int i=0; i<=n; i++) {
my_ints[i] = i+1;
}
do {
for (int j=0; j<n; j++) {
cout << my_ints[j] << " "; // print permutation
}
cout << endl;
// some sort of magic? permute in place
} while (next_permutation(my_ints, my_ints+n));
}
int main()
{
// take integer from stdin
int input;
cin >> input;
int n_permutations = factorial(input);
// print output to stdout
cout << n_permutations << endl;
permute_array(input);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment