Create a random permutation of 1..N in constant space

前端 未结 6 724
旧巷少年郎
旧巷少年郎 2020-11-30 04:30

I am looking to enumerate a random permutation of the numbers 1..N in fixed space. This means that I cannot store all numbers in a list. The reason for that is that N can be

6条回答
  •  时光取名叫无心
    2020-11-30 04:49

    Here's some SageMath code that should generate a random permutation the way Daniel Fischer suggested:

    def random_safe_prime(lbound):
        while True:
            q = random_prime(lbound, lbound=lbound // 2)
            p = 2 * q + 1
            if is_prime(p):
                return p, q
    
    
    def random_permutation(n):
        p, q = random_safe_prime(n + 2)
    
        while True:
            r = randint(2, p - 1)
            if pow(r, 2, p) != 1 and pow(r, q, p) != 1:
                i = 1
                while True:
                    x = pow(r, i, p)
                    if x == 1:
                        return
    
                    if 0 <= x - 2 < n:
                        yield x - 2
    
                    i += 1
    

提交回复
热议问题