如何交错两个数组? [英] How can I interleave two arrays?

查看:47
本文介绍了如何交错两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个数组,例如

If I have two arrays e.g

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

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

I would like to merge/interleave the arrays in the following pattern [one[0], two[0], one[1], two[1] etc....]

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

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

What would be a good way to implement the combining function?

func mergeFunction(one: [T], _ two: [T]) -> [T] {
    var mergedArray = [T]()
    //What goes here
    return mergedArray
}

推荐答案

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

If both arrays have the same length then this is a possible solution:

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 元素数组并连接结果.

Here zip() enumerates the arrays in parallel and returns a sequence of pairs (2-element tuples) with one element from each array. flatMap() creates a 2-element array from each pair and concatenates the result.

如果数组可以有不同的长度,那么你附加结果中较长数组的额外元素:

If the arrays can have different length then you append the extra elements of the longer array to the result:

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)
}

这篇关于如何交错两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆