Last active
November 30, 2017 04:06
-
-
Save fmela/070822f3db482dbefd54bdaa1e8d9f09 to your computer and use it in GitHub Desktop.
Enumerate every permutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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