V
V
vanyaseverin2019-06-04 14:22:10
Swift
vanyaseverin, 2019-06-04 14:22:10

How to get one combined array from 2 arrays in Swift?

There are 2 arrays:

var array1: [String] = ["l1", "m2", "r3"]
var array2: [String] = ["l4", "m5", "r6"]
var combinations:  = []

You need to combine array1 and array2 so that combinations are the result:
var combinations:  = [
["l1", "m2", "r3"], ["l1", "m5", "r3"], ["l1", "m5", "r6"], ["l1", "m2", "r6"],
["l4", "m2", "r3"], ["l4", "m5", "r3"], ["l4", "m5", "r6"], ["l4", "m2", "r6"]
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-04
@vanyaseverin

let arrays:  = [array1, array2]
var combinations:  = []

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question