2

順列を決定するためのコードを書こうとしていました。ウィキペディアには、(BR Heap からの) シンプルなアルゴリズムの疑似コードがあります。疑似コードを翻訳してみた

procedure generate(k : integer, A : array of any):
    if k = 1 then
        output(A)
    else
        // Generate permutations with kth unaltered
        // Initially k == length(A)
        generate(k - 1, A)

        // Generate permutations for kth swapped with each k-1 initial
        for i := 0; i < k-1; i += 1 do
            // Swap choice dependent on parity of k (even or odd)
            if k is even then
                swap(A[i], A[k-1]) // zero-indexed, the kth is at k-1
            else
                swap(A[0], A[k-1])
            end if
            generate(k - 1, A)

        end for
    end if

私のコードは順列の正しい数を示していますが、欠落しているものと倍増しているものがあることがわかります。

これは、Swift の値型と参照型の私の誤解に基づいていることが判明しました。

ここに私の(正しく動作していない)コードがあります:

func perms(k: Int, arr: [Any]) {   //NOTE that this is NOT providing the correct permuations at this time.  Some are doubled, some are missing (Yet the total permuations in number are correct)
    var variedArray = arr
    if k == 1 {
        counter += 1  //this is not part of the Wikipedia psuedo code, I just wanted to count that I was at least getting the right number of permutations
        outputArray.append(variedArray)  //this is appending to an array that contains all the permutation after all is done
        
    } else {
        
        perms(k: k - 1 , arr: variedArray)
        for i in 0..<k-1 {
            if (k)%2 == 0 {  // if even do this
                variedArray.swapAt(i, k-1)
            } else {
                variedArray.swapAt(0, k-1)
            }
            perms(k: k - 1, arr: variedArray)
        }
    }
    
    return
}
4

1 に答える 1