如何交错两个数组? zip(_:_ :) flatMap(_ :) sequence(state:next :) init(_ :)

问题描述 投票:11回答:3

如果我有两个数组,例如

let one = [1,3,5]
let two = [2,4,6]

我想以下列模式合并/交错数组[one [0],two [0],one [1],two [1] etc ....]

//prints [1,2,3,4,5,6]
let comibned = mergeFunction(one, two)
print(combined)

实现组合功能的好方法是什么?

func mergeFunction(one: [T], _ two: [T]) -> [T] {
    var mergedArray = [T]()
    //What goes here
    return mergedArray
}
arrays swift array-merge
3个回答
26
投票

如果两个数组具有相同的长度,那么这是一个可能的解决方案:

let one = [1,3,5]
let two = [2,4,6]

let merged = zip(one, two).flatMap { [$0, $1] }

print(merged) // [1, 2, 3, 4, 5, 6]

这里zip()并行枚举数组并返回一对(2元素元组)的序列,每个数组中有一个元素。 flatMap()从每对中创建一个2元素数组并连接结果。

如果数组可以具有不同的长度,那么您将更长数组的额外元素附加到结果:

func mergeFunction<T>(one: [T], _ two: [T]) -> [T] {
    let commonLength = min(one.count, two.count)
    return zip(one, two).flatMap { [$0, $1] } 
           + one.suffixFrom(commonLength)
           + two.suffixFrom(commonLength)
}

Swift 3更新:

func mergeFunction<T>(_ one: [T], _ two: [T]) -> [T] {
    let commonLength = min(one.count, two.count)
    return zip(one, two).flatMap { [$0, $1] } 
           + one.suffix(from: commonLength)
           + two.suffix(from: commonLength)
}

6
投票

如果您只是想交错两个数组,您可以执行以下操作:

let maxIndex = max(one.count, two.count)
var mergedArray = Array<T>()
for index in 0..<maxIndex {
    if index < one.count { mergedArray.append(one[index]) }
    if index < two.count { mergedArray.append(two[index]) }
}

return mergedArray

0
投票

使用Swift 5,您可以使用以下Playground示例代码之一来解决您的问题。


#1. Using zip(_:_:) function and Collection's flatMap(_:) method

let one = [1, 3, 5]
let two = [2, 4, 6]

let array = zip(one, two).flatMap({ [$0, $1] })
print(array) // print: [1, 2, 3, 4, 5, 6]

Apple states

如果传递给zip(_:_:)的两个序列长度不同,则得到的序列与较短序列的长度相同。


#2. Using sequence(state:next:) function

let one = [1, 3, 5]
let two = [2, 4, 6]

let unfoldSequence = sequence(state: (false, one.makeIterator(), two.makeIterator()), next: { state -> Int? in
    state.0.toggle()
    return state.0 ? state.1.next() : state.2.next()
})
let array = Array(unfoldSequence)
print(array) // print: [1, 2, 3, 4, 5, 6]

#3. Using AnyIterator's init(_:) initializer

let one = [1, 3, 5]
let two = [2, 4, 6]

var oneIterator = one.makeIterator()
var twoIterator = two.makeIterator()
var state = false

let anyIterator = AnyIterator<Int> {
    state.toggle()
    return state ? oneIterator.next() : twoIterator.next()
}

let array = Array(anyIterator)
print(array) // print: [1, 2, 3, 4, 5, 6]

作为替代方法,您可以将迭代器包装在AnySequence实例中:

let one = [1, 3, 5]
let two = [2, 4, 6]

let anySequence = AnySequence<Int>({ () -> AnyIterator<Int> in
    var oneIterator = one.makeIterator()
    var twoIterator = two.makeIterator()
    var state = false

    return AnyIterator<Int> {
        state.toggle()
        return state ? oneIterator.next() : twoIterator.next()
    }
})

let array = Array(anySequence)
print(array) // print: [1, 2, 3, 4, 5, 6]
© www.soinside.com 2019 - 2024. All rights reserved.