【问题标题】:Picking elements from multiple arrays从多个数组中挑选元素
【发布时间】:2014-09-09 12:37:51
【问题描述】:

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

这是一个例子:

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

myArray 元素的数量可能会有所不同,其中的数组也是如此。

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

【问题讨论】:

  • 向我们展示您目前编写的代码。
  • 我不知道如何解决这个问题,但我正在使用一些 for in 循环

标签: arrays swift


【解决方案1】:

利用https://stackoverflow.com/a/20049365/1187415的思路,可以这样 在 Swift 中完成

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

最后一个函数可以写得更快捷

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 功能。)


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

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]]

【讨论】:

  • 抱歉,我错过了reduce
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
相关资源
最近更新 更多