2D array in Swift examples
Q.1 Given a matrix find row-wise sum.
Sol>
var matrix = [
[1, -1, 4, 3],
[2, 6, -1, -2],
[6, -1, 0, 3]
]
func rowWiseSum(matrix: [[Int]]) {
for row in 0..<matrix.count {
var sum = 0
for col in 0..<matrix[row].count {
sum += matrix[row][col]
}
print(sum)
}
}
rowWiseSum(matrix: matrix)
o/p-
7
5
8
Q. Given a matrix find column-wise sum.
Sol>
var matrix = [
[1, -1, 4, 3],
[2, 6, -1, -2],
[6, -1, 0, 3]
]
Method – 1
func columnWiseSum(matrix: [[Int]]) {
let rowCount = matrix.count
let colCount = matrix[0].count
for col in 0..<colCount {
var sum = 0
for row in 0..<rowCount {
sum += matrix[row][col]
}
print(sum)
}
}
columnWiseSum(matrix: matrix)
0/p-
9
4
3
4
Method- 2
func columnWiseSum(matrix: [[Int]]) -> [Int] {
let rowCount = matrix.count
let colCount = matrix[0].count
var columnSums = [Int](repeating: 0, count: colCount)
for row in matrix {
print(“row: \(row.enumerated())“)
for (col, element) in row.enumerated() {
columnSums[col] += element
}
}
return columnSums
}
rowWiseSum(matrix: matrix)
o/p-
9
4
3
4