Algorithm for finding numerical permutation given lexicographic index

前端 未结 4 926
我在风中等你
我在风中等你 2020-11-28 12:53

I am looking for an algorithm that given a set of numbers (for example 1 2 3) and an index (for example 2) will get me the second permutation of those numbers according to a

4条回答
  •  无人及你
    2020-11-28 13:55

    Here is a simple solution:

    from math import factorial # python math library
    
    i = 5               # i is the lexicographic index (counting starts from 0)
    n = 3               # n is the length of the permutation
    p = range(1, n + 1) # p is a list from 1 to n
    
    for k in range(1, n + 1): # k goes from 1 to n
        f = factorial(n - k)  # compute factorial once per iteration
        d = i // f            # use integer division (like division + floor)
        print(p[d]),          # print permuted number with trailing space
        p.remove(p[d])        # delete p[d] from p
        i = i % f             # reduce i to its remainder
    

    Output:

    3 2 1
    

    The time complexity is O(n^2) if p is a list, and O(n) amortized if p is a hash table and factorial is precomputed.

提交回复
热议问题