我怎样才能交错两个数组? [英] How can I interleave two arrays?
问题描述
如果我有两个数组例如
因为一次= [1,3,5]
让两人= [2,4,6]
我想在下面的模式合并/交错数组[一[0],2个[0],[1],2个[1]等...]
//输出[1,2,3,4,5,6]
让comibned = mergeFunction(一,二)
打印(合并)
什么是实现组合功能的好办法?
FUNC mergeFunction(之一:[T],_二:[T]) - GT; [T] {
VAR mergedArray = [T]()
//善有善报这里
返回mergedArray
}
如果两个数组拥有的相同的长度的,那么这是一个可能的解决方案:
因为一次= [1,3,5]
让两人= [2,4,6]让合并后的ZIP =(一,二).flatMap {[$ 0 $ 1]}打印(合并)// [1,2,3,4,5,6]
下面的zip()
列举了平行阵列,并返回一个序列
的对(2-元件的元组)与来自每个阵列的一个元素。 flatMap()
创建一个从每对一个2单元阵列和并置的结果。
如果该阵列可以的不同长度的则追加
较长阵列的额外的元素的结果是:
FUNC mergeFunction< T>(之一:[T],_二:[T]) - GT; [T] {
让commonLength = MIN(one.count,two.count)
返回ZIP(一,二).flatMap {[$ 0 $ 1]}
+ one.suffixFrom(commonLength)
+ two.suffixFrom(commonLength)
}
If I have two arrays e.g
let one = [1,3,5]
let two = [2,4,6]
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]
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)
}
这篇关于我怎样才能交错两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!