1

Given an array of intergers. how to a program to print all the permutations of the numbers in the array. The output should be sorted in a non-increasing order. For example for the array { 12, 4, 66, 8, 9}, the output should be:

9866412

9866124

9846612

....

....

1246689
amudhan3093
  • 740
  • 9
  • 17
  • to get an array permutation see [here](http://stackoverflow.com/questions/2920315/permutation-of-array). Additionally, you have to perform a [sorting algorithm](http://www.sorting-algorithms.com/) (you can choose the one you prefer) on your array, and you're done. – MaVVamaldo Jul 31 '13 at 06:30
  • What language are you using? – Goatcat Jul 31 '13 at 07:47
  • I am using c++.Thank you,it worked – amudhan3093 Aug 01 '13 at 08:05

1 Answers1

0
#include<algorithm>
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int totaldigits=0;
int x[10000000];
int countx=0;
int finddigits(int num)
{
    int counter=0;
    while(num!=0)
    {
        num=num/10;
        counter++;
    }
    return counter;
}
int arrdigits(int *a,int size)
{
    int count=0;
    for(int i=0;i<=size;i++)
    {
    count+=finddigits(a[i]);
    }
    return count;
}
int findval(int n)
{
totaldigits-=finddigits(n);
return(pow(10,totaldigits)*n);
}
void findnum(int *a,int size)
{
    x[countx]=0;
    int n=0;
    for(int i=0;i<=size;i++)
    {
    n+=findval(a[i]);
    }
    x[countx]=n;
    countx++;
}
void swap(int *a,int *b)
{
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
void permute(int *arr,int start,int end)
{
if(start==end)
{
totaldigits=arrdigits(arr,end);
findnum(arr,end);
}
else
{
    for(int j=start;j<=end;j++)
    {
        swap(arr[start],arr[j]);
        permute(arr,start+1,end);
        swap(arr[start],arr[j]);  //BACKTRACK
    }
}
}
int main()
{
int a[]={12,4,66,8,9};
totaldigits=arrdigits(a,4);
permute(a,0,4);
sort(x,x+countx);
for(int i=countx-1;i>=0;i--)
fprintf(stdout,"%ld\n",x[i]);
system("pause");
return 0;
}
amudhan3093
  • 740
  • 9
  • 17