数学运算2D数组中的各个元素-Swift

时间:2019-04-04 04:58:54

标签: arrays swift math swift3 operation

我正在尝试对结合1D数组(mod)的2D数组(testArray)的各个元素执行不同的数学运算。我已经有了以下用于生成单个变量的方法,但无法弄清楚如何将这些值重新返回到新的2D数组中。雨燕3.0.2。

let testArray: [[Double]] =
    [[0,100,20.1],
     [1,99,19.2],
     [3,98,18.2],
     [5,97,17.3],
     [7,96,16.4],
     [9,95,15.5]]

let mod: [Double] = [0,5,7,14,20,22]

//Math operations on the two above arrays
for var x in 0..<testArray.count {
    var result1 = Double(testArray[x][0])
    var result2 = Double(testArray[x][1] + mod[x])
    var result3 = Double(testArray[x][2] - mod[x])
    print(result1,result2,result3)
}

//output is as follows:
0.0 100.0 20.1
1.0 104.0 14.2
3.0 105.0 11.2
5.0 111.0 3.3
7.0 116.0 -3.6
9.0 117.0 -6.5

//how do I get the same numbers into a new 2D array as follows:
[[0.0,100.0,20.1],
 [1.0,104.0,14.2],
 [3.0,105.0,11.2],
 [5.0,111.0,3.3],
 [7.0,116.0,-3.6],
 [9.0,117.0,-6.5]]

2 个答案:

答案 0 :(得分:0)

就这么简单

var anotherArray: [[Double]] = []
for x in 0..<testArray.count {
    let result1 = Double(testArray[x][0])
    let result2 = Double(testArray[x][1] + mod[x])
    let result3 = Double(testArray[x][2] - mod[x])
    anotherArray.append([result1, result2, result3])
}
print(anotherArray)

答案 1 :(得分:0)

您可以使用map

let result = testArray.indices.map { [ testArray[$0][0], testArray[$0][1] + mod[$0], testArray[$0][2] - mod[$0] ] }

在旁注中,您的for块可以写为:

for x in testArray.indices {
    let result1 = testArray[x][0]
    let result2 = testArray[x][1] + mod[x]
    let result3 = testArray[x][2] - mod[x]
    print(result1,result2,result3)
}