如何在Swift中将多个数组合并成一个具有交替值的数组?

时间:2021-11-14 08:08:28

How to merge several arrays into one array with alternating values?

如何将多个数组合并到一个具有交替值的数组中?

ex:

例:

var arr1 = [1, 2, 3, 4, 5]
var arr2 = [a, b, c, d, e, f, g]
var arr3 = [aa, bb, cc, dd]

to

[1, a, aa, 2, b, bb, 3, c, cc, 4, d, dd, 5, e, f, g]

[1,aa 2 b,bb,3 c,cc,4 d,dd,5,e,f,g)

5 个解决方案

#1


1  

I made a func for you. You could use several different arrays as an argument

我为你做了个有趣的事。可以使用几个不同的数组作为参数。

var arr1 = [1, 2, 3, 4, 5]
var arr2 = ["a", "b", "c", "d", "e", "f", "g"]
var arr3 = ["aa", "bb", "cc", "dd"]

func combine<T>(arrays:[[T]]) -> [T] {

    let maxCount = arrays.reduce(0) { max($0, $1.count) }

    var result = [T]()

    for i in 0..<maxCount {
        for array in arrays {
            if i < array.count {
                result.append(array[i])
            }
        }
    }

    return result

}

combine(arrays: [arr1,arr2,arr3] as [[Any]])
// or
combine(arrays: [arr2,arr3]) // if type is the same

#2


0  

No generic function for that I suppose but implementing it is rather simple:

我认为没有通用的函数,但是实现它是相当简单的:

    var sumArr: [Any] = []
    let max_count = max(arr1.count, arr2.count, arr3.count)
    for i in 0...max_count {
        if arr1.count > i { sumArr.append(arr1[i]) }
        if arr2.count > i { sumArr.append(arr2[i]) }
        if arr3.count > i { sumArr.append(arr3[i]) }
     }

or let's make it more reusable:

或者让它更可重用:

    func combineArrays(arrays: [[Any]]) -> [Any] {
        var sumArr: [Any] = []
        guard let max_count = arrays.map({$0.count}).max() else { return [] }
        for i in 0...max_count {
            for arr in arrays {
                if arr.count > i { sumArr.append(arr[i]) }
            }
        }
        return sumArr
    }

#3


0  

You can try this

你可以试试这个

var c = 0
var i = 0
var arr1 = [1, 2, 3, 4, 5]
var arr2 = [a, b, c, d, e, f, g]
var arr3 = [aa, bb, cc, dd]
var arr = [] 
while (c < 3) {
    if i < arr1.count {
        arr.append(arr1[i])
    } else {
        c += 1
    }
    if i < arr2.count {
        arr.append(arr2[i])
    } else {
        c += 1
    }
    if i < arr3.count {
        arr.append(arr3[i])
    } else {
        c += 1
    }
    i += 1
}

#4


0  

If the elements are of the same type in the 3 arrays, you could use zip and flatMap to merge them.

如果3个数组中的元素具有相同的类型,可以使用zip和flatMap来合并它们。

For example:

例如:

var arr1 = ["1", "2", "3", "4", "5"]
var arr2 = ["a", "b", "c", "d", "e", "f", "g"]
var arr3 = ["aa", "bb", "cc", "dd","ee"]

let merged = [arr1,arr2,arr3]
             .reduce(Array<Array<String>>())
             { zip($0,$1).map{$0+[$1]} + $0.dropFirst($1.count) + $1.dropFirst($0.count).map{[$0]} }
             .flatMap{$0}

[EDIT] Or if you want a more generalized solution for any number of arrays, you could create a function to do it:

[编辑]或者如果你想为任意数量的数组创建一个更通用的解决方案,你可以创建一个函数来实现:

func transpose<T>(_ matrix:[[T]]) -> [[T]]
{
  return matrix.reduce([[T]]())
         {
           zip($0,$1).map{$0+[$1]} 
           + $0.dropFirst($1.count) 
           + $1.dropFirst($0.count).map{[$0]} 
         }
}

func mergeArrays<T>(_ a:[T] ...) -> [[T]]
{ 
  return transpose(a).flatMap{$0}
}

let merged = mergeArrays(arr1,arr3,arr5)

#5


0  

Try this:

试试这个:

extension Array {

    //Mutating
    mutating func weave(with array: Array) -> Array {
        precondition(!isEmpty && !array.isEmpty)
        var weavedArray = Array<Element>()
        weavedArray.reserveCapacity(count + array.count)
        var inputArray = array
        for _ in 0..<[count, array.count].min()! {
            weavedArray.append(self.removeFirst())
            weavedArray.append(inputArray.removeFirst())
        }
        let largerArr = largerOf(self, inputArray)
        if largerArr.count != 0 {
            weavedArray.append(contentsOf: largerArr)
        }
        self = weavedArray
        return weavedArray
    }

    //Non-mutating
    func weaved(with array: Array) -> Array {
        precondition(!isEmpty && !array.isEmpty)
        var weavedArray = Array<Element>()
        weavedArray.reserveCapacity(count + array.count)
        var selfArray = self
        var inputArray = array
        for _ in 0..<[count, array.count].min()! {
            weavedArray.append(selfArray.removeFirst())
            weavedArray.append(inputArray.removeFirst())
        }
        let largerArr = largerOf(selfArray, inputArray)
        if largerArr.count != 0 {
            weavedArray.append(contentsOf: largerArr)
        }
        return weavedArray
    }

    internal func largerOf<T>(_ arr1: Array<T>, _ arr2: Array<T>) -> Array<T> {
        switch (arr1.count, arr2.count) {
        case (let a, let b) where a > b: return arr1
        case (let a, let b) where a < b: return arr2
        case (let a, let b) where a == b: return arr1
        default: return arr2
        }
    }
}

Usage

Mutating - .weave(with: )

变异——.weave(:)

let odds = [1, 3, 5, 7, 9]
let evens = [2, 4, 6, 8, 10]

odds.weave(with: evens)

print(odds) //prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(evens) //prints: [2, 4, 6, 8, 10]

Non-Mutating - .weaved(with: )

与:Non-Mutating .weaved()

let odds = [1, 3, 5, 7, 9]
let evens = [2, 4, 6, 8, 10]

let firstTen = odds.weaved(with: evens)

print(firstTen) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(odds) //prints: [1, 3, 5, 7, 9]
priny(evens) //prints: [2, 4, 6, 8, 10]

Hope this helps, if you have any further questions, feel free to ask!

希望这对你有所帮助,如果你有任何问题,请尽管问!

#1


1  

I made a func for you. You could use several different arrays as an argument

我为你做了个有趣的事。可以使用几个不同的数组作为参数。

var arr1 = [1, 2, 3, 4, 5]
var arr2 = ["a", "b", "c", "d", "e", "f", "g"]
var arr3 = ["aa", "bb", "cc", "dd"]

func combine<T>(arrays:[[T]]) -> [T] {

    let maxCount = arrays.reduce(0) { max($0, $1.count) }

    var result = [T]()

    for i in 0..<maxCount {
        for array in arrays {
            if i < array.count {
                result.append(array[i])
            }
        }
    }

    return result

}

combine(arrays: [arr1,arr2,arr3] as [[Any]])
// or
combine(arrays: [arr2,arr3]) // if type is the same

#2


0  

No generic function for that I suppose but implementing it is rather simple:

我认为没有通用的函数,但是实现它是相当简单的:

    var sumArr: [Any] = []
    let max_count = max(arr1.count, arr2.count, arr3.count)
    for i in 0...max_count {
        if arr1.count > i { sumArr.append(arr1[i]) }
        if arr2.count > i { sumArr.append(arr2[i]) }
        if arr3.count > i { sumArr.append(arr3[i]) }
     }

or let's make it more reusable:

或者让它更可重用:

    func combineArrays(arrays: [[Any]]) -> [Any] {
        var sumArr: [Any] = []
        guard let max_count = arrays.map({$0.count}).max() else { return [] }
        for i in 0...max_count {
            for arr in arrays {
                if arr.count > i { sumArr.append(arr[i]) }
            }
        }
        return sumArr
    }

#3


0  

You can try this

你可以试试这个

var c = 0
var i = 0
var arr1 = [1, 2, 3, 4, 5]
var arr2 = [a, b, c, d, e, f, g]
var arr3 = [aa, bb, cc, dd]
var arr = [] 
while (c < 3) {
    if i < arr1.count {
        arr.append(arr1[i])
    } else {
        c += 1
    }
    if i < arr2.count {
        arr.append(arr2[i])
    } else {
        c += 1
    }
    if i < arr3.count {
        arr.append(arr3[i])
    } else {
        c += 1
    }
    i += 1
}

#4


0  

If the elements are of the same type in the 3 arrays, you could use zip and flatMap to merge them.

如果3个数组中的元素具有相同的类型,可以使用zip和flatMap来合并它们。

For example:

例如:

var arr1 = ["1", "2", "3", "4", "5"]
var arr2 = ["a", "b", "c", "d", "e", "f", "g"]
var arr3 = ["aa", "bb", "cc", "dd","ee"]

let merged = [arr1,arr2,arr3]
             .reduce(Array<Array<String>>())
             { zip($0,$1).map{$0+[$1]} + $0.dropFirst($1.count) + $1.dropFirst($0.count).map{[$0]} }
             .flatMap{$0}

[EDIT] Or if you want a more generalized solution for any number of arrays, you could create a function to do it:

[编辑]或者如果你想为任意数量的数组创建一个更通用的解决方案,你可以创建一个函数来实现:

func transpose<T>(_ matrix:[[T]]) -> [[T]]
{
  return matrix.reduce([[T]]())
         {
           zip($0,$1).map{$0+[$1]} 
           + $0.dropFirst($1.count) 
           + $1.dropFirst($0.count).map{[$0]} 
         }
}

func mergeArrays<T>(_ a:[T] ...) -> [[T]]
{ 
  return transpose(a).flatMap{$0}
}

let merged = mergeArrays(arr1,arr3,arr5)

#5


0  

Try this:

试试这个:

extension Array {

    //Mutating
    mutating func weave(with array: Array) -> Array {
        precondition(!isEmpty && !array.isEmpty)
        var weavedArray = Array<Element>()
        weavedArray.reserveCapacity(count + array.count)
        var inputArray = array
        for _ in 0..<[count, array.count].min()! {
            weavedArray.append(self.removeFirst())
            weavedArray.append(inputArray.removeFirst())
        }
        let largerArr = largerOf(self, inputArray)
        if largerArr.count != 0 {
            weavedArray.append(contentsOf: largerArr)
        }
        self = weavedArray
        return weavedArray
    }

    //Non-mutating
    func weaved(with array: Array) -> Array {
        precondition(!isEmpty && !array.isEmpty)
        var weavedArray = Array<Element>()
        weavedArray.reserveCapacity(count + array.count)
        var selfArray = self
        var inputArray = array
        for _ in 0..<[count, array.count].min()! {
            weavedArray.append(selfArray.removeFirst())
            weavedArray.append(inputArray.removeFirst())
        }
        let largerArr = largerOf(selfArray, inputArray)
        if largerArr.count != 0 {
            weavedArray.append(contentsOf: largerArr)
        }
        return weavedArray
    }

    internal func largerOf<T>(_ arr1: Array<T>, _ arr2: Array<T>) -> Array<T> {
        switch (arr1.count, arr2.count) {
        case (let a, let b) where a > b: return arr1
        case (let a, let b) where a < b: return arr2
        case (let a, let b) where a == b: return arr1
        default: return arr2
        }
    }
}

Usage

Mutating - .weave(with: )

变异——.weave(:)

let odds = [1, 3, 5, 7, 9]
let evens = [2, 4, 6, 8, 10]

odds.weave(with: evens)

print(odds) //prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(evens) //prints: [2, 4, 6, 8, 10]

Non-Mutating - .weaved(with: )

与:Non-Mutating .weaved()

let odds = [1, 3, 5, 7, 9]
let evens = [2, 4, 6, 8, 10]

let firstTen = odds.weaved(with: evens)

print(firstTen) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(odds) //prints: [1, 3, 5, 7, 9]
priny(evens) //prints: [2, 4, 6, 8, 10]

Hope this helps, if you have any further questions, feel free to ask!

希望这对你有所帮助,如果你有任何问题,请尽管问!