我有两个数组:
var array1: [String] = ["l1", "m2", "r3"]
var array2: [String] = ["l4", "m5", "r6"]
如何将它们组合成一个看起来像
的数组var combinations: [[String]] = [
["l1", "m2", "r3"], ["l1", "m5", "r3"], ["l1", "m5", "r6"], ["l1", "m2", "r6"],
["l4", "m2", "r3"], ["l4", "m5", "r3"], ["l4", "m5", "r6"], ["l4", "m2", "r6"]
]
编辑1 :如果您有两个以上的数组
let arrays: [[String]] = [array1, array2, moreArrays]
var combinations: [[String]] = []
let arraysLen: Int = arrays.count
let arrLen: Int = arrays[0].count
let numCombinations: Int = Int(pow(Double(arraysLen), Double(arrLen)))
for i in (0 ..< numCombinations) {
var combination: [String] = []
for j in (0 ..< arrLen) {
let arrIndex: Int = i / Int(pow(Double(arraysLen), Double(j))) % arraysLen
let elIndex: Int = arrLen - j - 1
combination.insert(arrays[arrIndex][elIndex], at: 0)
}
combinations.append(combination)
}
答案 0 :(得分:1)
如果要获得两个数组的可能组合,可以使用一个简单的技巧:
var array1: [String] = ["l1", "m2", "r3"]
var array2: [String] = ["l4", "m5", "r6"]
guard array1.count == array2.count else {
fatalError("Array must be of the same lenght")
}
let numCombinations = 1 << array1.count
let combinations: [[String]] = (0..<numCombinations).map { (index: Int) in
return Array((0..<array1.count).map { (elementIndex: Int) in
// every bit decides which array to choose
let chooseArray1 = (index & (1 << elementIndex)) == 0
return chooseArray1 ? array1[elementIndex] : array2[elementIndex]
})
}
print(combinations) // [["l1", "m2", "r3"], ["l4", "m2", "r3"], ["l1", "m5", "r3"], ["l4", "m5", "r3"], ["l1", "m2", "r6"], ["l4", "m2", "r6"], ["l1", "m5", "r6"], ["l4", "m5", "r6"]]
答案 1 :(得分:1)
如果两个数组计数相同,则在每次迭代中都从原始数组迭代两个数组并交换对象,并将其追加到结果中。
var combinations: [[String]] = []
if array1.count == array2.count {
combinations.append(array1)
combinations.append(array2)
for i in 0..<array1.count {
var arr1 = array1
var arr2 = array2
(arr1[i], arr2[i]) = (arr2[i], arr1[i])
combinations.append(arr1)
combinations.append(arr2)
}
print(combinations)
}
[[“ l1”,“ m2”,“ r3”],[“ l4”,“ m5”,“ r6”],[“ l4”,“ m2”,“ r3”],[“ l1” , “ m5”,“ r6”],
[“ l1”,“ m5”,“ r3”],[“ l4”,“ m2”,“ r6”],[“ l1”,“ m2”, “ r6”],[“ l4”,“ m5”,“ r3”]]