Wednesday, 17 December 2014

Lexicographic permutations Problem 24 Project euler

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012   021   102   120   201   210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

ALGORITHM::
There will be 9! combination possible when first digit is fixed to zero.Similarly for 1 and 2.But when we further add 9! the sum will exceed 1 million so now first digit is fixed i.e 2.Similarly proceed the same way and fix rest of all the digit.
C CODE::
#include<stdio.h>
static int a[10];
int fact(int n)
{
    if(n>=1)return n*fact(n-1);
    if(n==0){return 1; }
    if(n<0){return 0;}
}
main()
{
    int counter=0;
    int i=0;
    int l=1000000;
    while(l>0)
    {
        while(l>0)
        {
            l=l-fact(9-i);
            counter++;
            a[i]++;
            int j,y=1;
            while(y!=0)
            {
             y=0;

            for(j=0;j<i;j++)
            {
                if(a[j]==a[i]){a[i]++;y++;}
            }
            }
        }
        int j,y=1;;
        a[i]--;


            while(y!=0)
            {
                y=0;
            for(j=0;j<i;j++)
            {

                if(a[j]==a[i]){a[i]--;y++;}
            }
            }
            l=l+fact(9-i);
            if(l==1)break;;
            i++;
}
for(i=0;i<10;i++)
printf("%d",a[i]);
}
TIME TAKEN:
10ms
RESULT:
2783915460

No comments:

Post a Comment