Skip to content

Instantly share code, notes, and snippets.

@janosgyerik
Created March 1, 2013 08:12
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 janosgyerik/5063197 to your computer and use it in GitHub Desktop.
Save janosgyerik/5063197 to your computer and use it in GitHub Desktop.
A program to print all possible arrangements of `n` numbers. It accepts `n` as a command line parameter. Be careful, as there are `n!` possible permutations. With `n=10` or greater the program will be extremely slow.
#include <stdio.h>
#include <stdlib.h>
void rearrange(int *numbers, int index, int num) {
int tmp;
for (int i = index; i < num; ++i) {
tmp = numbers[index];
numbers[index] = numbers[i];
numbers[i] = tmp;
rearrange(numbers, index + 1, num);
numbers[i] = numbers[index];
numbers[index] = tmp;
}
if (index == num - 1) {
for (int i = 0; i < num; ++i) {
printf("%d ", numbers[i]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int num = atoi(argv[1]);
int *numbers = new int[num];
for (int i = 0; i < num; ++i) {
numbers[i] = i + 1;
}
rearrange(numbers, 0, num);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment