Algorithm to apply permutation in constant memory space

后端 未结 8 1565
温柔的废话
温柔的废话 2020-12-13 21:29

I saw this question is a programming interview book, here I\'m simplifying the question.

Assume you have an array A of length n, and you ha

相关标签:
8条回答
  • 2020-12-13 22:04

    I agree with many solutions here, but below is a very short code snippet that permute throughout a permutation cycle:

    def _swap(a, i, j):
        a[i], a[j] = a[j], a[i]
    
    
    def apply_permutation(a, p):
        idx = 0
        while p[idx] != 0:
            _swap(a, idx, p[idx])
            idx = p[idx]
    

    So the code snippet below

    a = list(range(4))
    p = [1, 3, 2, 0]
    apply_permutation(a, p)
    print(a)
    

    Outputs [2, 4, 3, 1]

    0 讨论(0)
  • 2020-12-13 22:06

    You can consequently put the desired element to the front of the array, while working with the remaining array of the size (n-1) in the the next iteration step.

    The permutation array needs to be accordingly adjusted to reflect the decreasing size of the array. Namely, if the element you placed in the front was found at position "X" you need to decrease by one all the indexes greater or equal to X in the permutation table.

    In the case of your example:

    array                   permutation -> adjusted permutation
    
    A  =  {[a  b  c  d  e]}                 [4 3 2 0 1]
    A1 =  { e [a  b  c  d]}   [3 2 0 1] ->    [3 2 0 1] (decrease all indexes >= 4)
    A2 =  { e  d [a  b  c]}     [2 0 1] ->      [2 0 1] (decrease all indexes >= 3)
    A3 =  { e  d  c [a  b]}       [0 1] ->        [0 1] (decrease all indexes >= 2)
    A4 =  { e  d  c  a [b]}         [1] ->          [0] (decrease all indexes >= 0)
    

    Another example:

    A0 = {[a  b  c  d  e]}                  [0 2 4 3 1]
    A1 = { a [b  c  d  e]}     [2 4 3 1] ->   [1 3 2 0] (decrease all indexes >= 0)
    A2 = { a  c [b  d  e]}       [3 2 0] ->     [2 1 0] (decrease all indexes >= 2)
    A3 = { a  c  e [b  d]}         [1 0] ->       [1 0] (decrease all indexes >= 2)
    A4 = { a  c  e  d [b]}           [0] ->         [0] (decrease all indexes >= 1)
    

    The algorithm, though not the fastest, avoids the extra memory allocation while still keeping the track of the initial order of elements.

    0 讨论(0)
提交回复
热议问题