-
c program to print all possible combinations of given input number or value ?
about 8 years ago
-
about 8 years ago
Hello Krish, This solution will definitely help you, It will generate all the permutation of a given number without repetition. Actually it will generate number further after entered number, If you need all permutation, please remove comment of sort function call. What is done in the below implementation is that we had broken the number into unit digits and saved into an array. After this we look to find any element with smaller value then the preceding one for this we are traversing from higher index side to lower side. if any match found element at that index is swapped with element having just larger value on the upper side of array from index+1 to length of array. After swapping upper side of array from index + 1 to length of the array had to be sorted in increasing order. Repeat this steps until we don't have any possibilities.
#include <stdio.h> int possible(int arr[], int n) { int i; for (i = n-1; i > 0; i--) if (arr[i] > arr[i-1]) return 1; return 0; } void print(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d",arr[i]); printf("\n"); } void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } int partition (int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); int j; for ( j = low; j <= high- 1; j++) { if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } void nextNumber(int arr[], int n) { int i, j; int currentMin = 1000000; int index; int temp; for ( i = n-1; i > 0; i--) { if (arr[i] > arr[i-1]) { for ( j = i; j < n; j++) { if (arr[i-1] < arr[j] && currentMin > arr[j]) { currentMin = arr[j]; index = j; } } temp = arr[i-1]; arr[i-1] = arr[index]; arr[index] = temp; quickSort(arr,i,n-1); break; } } return; } int main() { int num; int tmp; int len = 0; int i; scanf("%d",&num); tmp = num; while (tmp) { tmp /= 10; len++; } int arr[len]; for (i = len-1; i >= 0; i--) { arr[i] = num%10; num /= 10; } // quickSort(arr,0,len-1); //remove this comment to generate all possibilities while(1) { print(arr,len); if(possible(arr,len)) { nextNumber(arr,len); } else { printf("No further possibilities\n"); break; } } return 0; }
You can also opt for the other approach which is quite easy from here http://findnerd.com/account#url=/list/view/Generating-all-possible-permutation-of-a-given-range/13953/
Hope this will help, any suggestions are welcomed :)
-
about 8 years ago
Please visit the following link and download the PDF file for more clear understanding. http://www.filedropper.com/krishproblemsolution
-
2 Answer(s)