I'm having a 2d array and I want to use something similar to flatMap and reduce together with a range of each of the two dimension. In my example I want to add each number from position 1 to 3 in each row 0 to 2.
My code at the moment looks similar to the following and it does work.
let array = [
[3,6,8,4],
[3,7,4,6],
[2,4,5,7],
[5,3,7,4]
]
let row = 1
let col = 2
var reducedValue = 0
(row-1...row+1).forEach {
reducedValue = array[$0][col-1...col+1].compactMap { $0 }.reduce(reducedValue, +)
}
The expected output is:
51
//6 + 8 + 4 + 7 + 4 + 6 + 4 + 5 + 7
However I was wondering if there is a solution similar to the this one:
reducedValue = array[row-1...row+1][col-1...col+1].compactMap { $0 }.reduce(0, +)
Or maybe even without the compactMap similar to this:
reducedValue = array[row-1...row+1][col-1...col+1].reduce(0, +)