I'm writing a program to print out all permutations of a given set of numbers in a random order i.e. if the user selects 3 then it should print: (0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1) and (2,1,0)
In my code I'm not getting all of the numbers that it's supposed to print. If I enter 3 I get: (2,1,2), (1,0,1),(0,1,0),(1,2,1),(2,1,2),(1,0,1)
Can anyone give me guidance on this algorithm? Thanks in advance...
Code:#include <stdio.h> int main() { // initialization of variables int Choice, Number, Temp; // counters int index, j, k; int Sets = 1; printf("What number would you like to go to?\n"); scanf("%d", &Choice); // initialize array after choice is made int NumArray[Choice]; // zero out array for(index=0; index<Choice; index++) { NumArray[index]=0; } // fill up array with numbers for(index=0; index<Choice; index++) { Number = index; NumArray[index] = Number; } // get number of sets for(index=Choice; index>0; index--) { Sets = Sets * index; } // permutation algorithm for(index=0; index<Sets; index++) { for(j=0; j<Choice; j++) { for(k=Choice; k>0; --k) { Temp = NumArray[j]; NumArray[j] = NumArray[k]; NumArray[k] = Temp; } printf("%d",Temp); } printf("\n"); } printf("There are %d possible sets!\n", Sets); return 0; }



LinkBack URL
About LinkBacks



