Monday 29 May 2017

Factorial Number System or factoradic

It is used for solving permutation problems. Generally with the help of this concept we can find the permutation string at Kth position.The factorial number system term was used first time by "Knuth".
Here is a code which was asked in Amazon Hiring Challenge to print the Kth permuted string.

Python code:



def result(p,ls):
    rem=[]
    z=0
    x=1
    while p!=0:
        z=p%x
        rem.append(z)
        p=p//x
        x=x+1
    rem=rem[::-1]
    rem1=list(map(int,rem))
    
    how_many=0
    if len(rem1)!=len(ls):
        how_many=len(ls)-len(rem1)
        #print(how_many)
        for go in range(how_many): 
            rem1.insert(0,0)
    g=[]
    #print(rem1)
    for l in range(len(ls)):
        v=rem1[l]
        st=ls[v]
        g.append(st)
        ls.remove(ls[v])
        #print(ls)
    return "".join(g)
t=int(input())

#print(type(t))
for i in range(t):
    strr,p=input().split()
    #print(strr) 
    P=int(p)
    ls=list(strr)
    gh=str(result(P-1,ls))
    print(gh)

  Input                         output
  1                          adbc
  abcd 5 
        
        

No comments:

Post a Comment