Given a permutation's lexicographic number, is it possible to get any item in it in O(1)

后端 未结 5 1149
不知归路
不知归路 2021-02-05 06:10

I want to know whether the task explained below is even theoretically possible, and if so how I could do it.

You are given a space of N elements (i.e. all

5条回答
  •  忘掉有多难
    2021-02-05 06:45

    After some research in Wikipedia, I desgined this algorithm:

    def getPick(fact_num_list):
        """fact_num_list should be a list with the factorial number representation, 
        getPick will return a tuple"""
        result = [] #Desired pick
        #This will hold all the numbers pickable; not actually a set, but a list
        #instead
        inputset = range(len(fact_num_list)) 
        for fnl in fact_num_list:
            result.append(inputset[fnl])
            del inputset[fnl] #Make sure we can't pick the number again
        return tuple(result)
    

    Obviously, this won't reach O(1) due the factor we need to "pick" every number. Due we do a for loop and thus, assuming all operations are O(1), getPick will run in O(n).

    If we need to convert from base 10 to factorial base, this is an aux function:

    import math
    
    def base10_baseFactorial(number):
        """Converts a base10 number into a factorial base number. Output is a list
        for better handle of units over 36! (after using all 0-9 and A-Z)"""
        loop = 1
        #Make sure n! <= number
        while math.factorial(loop) <= number:
            loop += 1
        result = []
        if not math.factorial(loop) == number:
            loop -= 1 #Prevent dividing over a smaller number than denominator
        while loop > 0:
            denominator = math.factorial(loop)
            number, rem = divmod(number, denominator)
            result.append(rem)
            loop -= 1
        result.append(0) #Don't forget to divide to 0! as well!
        return result
    

    Again, this will run in O(n) due to the whiles.

    Summing all, the best time we can find is O(n).

    PS: I'm not a native English speaker, so spelling and phrasing errors may appear. Apologies in advance, and let me know if you can't get around something.

提交回复
热议问题