Skip to content

Instantly share code, notes, and snippets.

@fmela
Last active November 30, 2017 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmela/070822f3db482dbefd54bdaa1e8d9f09 to your computer and use it in GitHub Desktop.
Save fmela/070822f3db482dbefd54bdaa1e8d9f09 to your computer and use it in GitHub Desktop.
Enumerate every permutation
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
bool next_permutation(unsigned a[], unsigned n)
{
if (n <= 1)
return false;
unsigned i = n-2;
while (!(a[i] < a[i+1]))
if (i-- == 0)
return false;
assert(a[i] < a[i+1]);
unsigned j = n-1;
while (!(a[j] > a[i]))
--j;
assert(j > i);
assert(a[j] > a[i]);
unsigned t = a[i]; a[i] = a[j]; a[j] = t;
for (++i, j=n-1; i < j; ++i, --j) {
t = a[i]; a[i] = a[j]; a[j] = t;
}
return true;
}
int main()
{
unsigned a[10];
const unsigned n = sizeof(a) / sizeof(a[0]);
for (unsigned i=0; i<n; ++i)
a[i] = i+1;
unsigned p = 0;
do {
printf("%u:", ++p);
for (unsigned i=0; i<n; ++i)
printf(" %u", a[i]);
printf("\n");
} while (next_permutation(a, n));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment