0
4

3 回答 3

1

从集合到自身的双射函数是置换。如果集合由从零开始的连续整数组成,则排列可以表示为数组。

在您的情况下,从 [0, 1, 2] 到自身的映射定义为

0 -> 1, 1 -> 2, 2 -> 0

将表示为数组[1, 2, 0]。“从左到右”的映射就变成了一个下标操作:

let perm = [1, 2, 0]

print(perm[1]) // 2

“从右到左”的映射是逆排列,也可以表示为数组:

func inversePermution(of perm: [Int]) -> [Int]? {
    var inverse: [Int] = Array(repeating: -1, count: perm.count)
    for (idx, elem) in perm.enumerated() {
        // Check for valid entries:
        guard elem >= 0 && elem < perm.count else { return nil }
        // Check for duplicate entries:
        guard inverse[elem] == -1 else { return nil }
        // Set inverse mapping:
        inverse[elem] = idx
    }
    return inverse
}

(这只是为了演示一般的想法。当然你可以把 this 做成一个Array扩展方法,或者Permutation用 this 和更多的方法定义一个类型。)

在您的示例中:

if let invPerm = inversePermution(of: perm) {
    print(invPerm) // [2, 0, 1]

    print(invPerm[2]) // 1
}
于 2019-06-25T19:00:26.013 回答
0

你可以使用zip(_:_:)on array,即

let arr1 = [0,1,2]
let arr2 = [01,2,0]

let result = Array(zip(arr1,arr2))

print(result) //Output: [(0, 1), (1, 2), (2, 0)]
于 2019-06-24T05:18:13.737 回答
0

我完成的代码:

import Foundation

public struct BidirectionalMapNonUnique<Left, Right> where Left: Hashable, Right: Hashable {
    private let ltr: [Left: Right]
    public let rtl: [Right: Left]

    public init(_ ltrMapping: [Left: Right]) {
        var rtlPending = [Right: Left]()
        for (key, value) in ltrMapping {
            rtlPending[value] = key
        }
        self.ltr = ltrMapping
        self.rtl = rtlPending
    }

    public func leftFrom(right: Right) -> Left {
        return rtl[right]!
    }

    public func rightFrom(left: Left) -> Right {
        return ltr[left]!
    }
}


let example = BidirectionalMapNonUnique<Int, Int>([0:10, 1:11, 2:12])

print(example.leftFrom(right: 11)) // Prints 1
print(example.rightFrom(left: 0)) // Prints 10
于 2019-06-24T06:02:59.537 回答