Created
March 1, 2013 08:12
-
-
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.
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 <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