Advertisement
Guest User

generateLists.c

a guest
Feb 28th, 2013
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void swap(int *num1, int *num2) { // standard swap function
  4.   int temp; // temporary var
  5.  
  6.   temp = *num1;  // store to temp
  7.   *num1 = *num2; // swap it
  8.   *num2 = temp;  // swap it again :D
  9. }
  10.  
  11. int rearange(int *numbers, int index, int num, int fact) {
  12.   swap(&numbers[index], &numbers[index-1]); // swap number at index with the one behind it
  13.  
  14.   /*int temp = numbers[index];
  15.   numbers[index] = numbers[index-1];
  16.   numbers[index-1] = temp;*/
  17.  
  18.   int i;
  19.   for (i = 1; i <= num; ++i) // print the current sequence
  20.   {
  21.     printf("%d ", numbers[i]);
  22.   }
  23.   printf("\n");
  24.  
  25.   fact--;  // decrement how many sequences remain
  26.   index--; // decrement our index in the array
  27.  
  28.   if (index > 1) {
  29.     if (fact > 0)                                                       // If we have more sequences remaining
  30.        rearange(numbers, index, num, fact);
  31.   } else {
  32.     return fact;
  33.   }// Do it all again! :D
  34. }
  35.  
  36. int main() {
  37.   int num, i; // our number and a counter
  38.  
  39.   printf("Enter a number less than 10: ");
  40.   scanf("%d", &num); // get the number from the user
  41.  
  42.   int numbers[11]; // create an array of appropriate size
  43.   // fill array
  44.   for (i = 1; i <= num; i++) { // fill the array from 1 to num
  45.     numbers[i] = i;
  46.   }
  47.  
  48.   int fact = 1; // calculate the factorial to determine
  49.   for (i = 1; i <= num; ++i) // how many possible sequences
  50.   {
  51.     fact = fact * i;
  52.   }
  53.  
  54.   do {
  55.     fact = rearange(numbers, num, num, fact);
  56.   } while (fact > 0);
  57.  
  58.   //rearange(numbers, num, num, fact); // begin rearranging by recursion
  59.  
  60.   return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement