从多个数组中挑选元素 [英] Picking elements from multiple arrays

查看:83
本文介绍了从多个数组中挑选元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中从多个数组中获取所有可能的元素组合?

How to get all the possible combinations of elements from multiple arrays in Swift?

这里是一个示例:

let myArray = [[2,3,4],
[1,2,3,4,5],
[1,2],
]

myArray 元素可能有所不同,其中的数组也一样。

The count of myArray elements may vary, same goes for the arrays inside it.

代码应该通过一次从每个数组中选择一个元素来输出数组,这看起来很基本,但是我可以现在看不到

The code should output an array by picking one element from each array at a time, seems basic but I can't see it now

推荐答案

使用https://stackoverflow.com/a/20049365/1187415 ,这可以是
在Swift中完成,

Using the ideas from https://stackoverflow.com/a/20049365/1187415, this can be done in Swift as

// Append all elements of a2 to each element of a1
func combihelper(a1 : [[Int]], a2 : [Int]) -> [[Int]] {
    var result = [[Int]]()
    for elem1 in a1 {
        for elem2 in a2 {
            result.append(elem1 + [elem2])
        }
    }
    return result
}

func combinations(array : [[Int]]) -> [[Int]] {
    // Start with the "empty combination" , then successively
    // add combinations with each row of array:
    var result : [[Int]] = [[]]
    for row in array {
        result = combihelper(result, row)
    }
    return result
}

最后一个函数可以更迅速地编写为

The last function can be written more Swiftly as

func combinations(array : [[Int]]) -> [[Int]] {
    return reduce(array, [[]]) { combihelper($0, $1) }
}

示例:

let myArray = [[1],
    [2,3,4],
    [5,6],
]
let result = combinations(myArray)
println(result)
// [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]]

(如果输入不限于整数,则可以替换 Int 中的
函数中的 Any 。)

(If your input is not restricted to integers, you can replace Int by Any in above functions.)

更新 Swift 3 并作为通用函数,因此它可以与
一起用于任何元素类型:

Update for Swift 3 and as a generic function, so that it can be used with any element type:

func combihelper<T>(a1 : [[T]], a2 : [T]) -> [[T]] {
    var result = [[T]]()
    for elem1 in a1 {
        for elem2 in a2 {
            result.append(elem1 + [elem2])
        }
    }
    return result
}

func combinations<T>(of array: [[T]]) -> [[T]] {
    return array.reduce([[]]) { combihelper(a1: $0, a2: $1) }
}


let myArray = [[1],
               [2,3,4],
               [5,6],
]

let result = combinations(of: myArray)
print(result) // [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]]

这篇关于从多个数组中挑选元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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