Scala iterate 2D array without for\while

Hello,
I’m new to scala and move from C\Cpp so my general think of accesing array elements (and surely arrays of arrays) is now changed (though for\while loops work in scala my co team told me to change my style to a more functional one). Now to my question after this introduction.

I have a 2D array (of integers) like
Array(Array(10,1),(20,2),(30,1),(40,3))
And I want partual sums of the second coordinate, such that each one will store the sum of its all previous ones (+the current one), on the example I gave this should yield
(10,1),(20,3),(30,4),(40,7)).

In C the code would look like: (assuming A is the name of the 2D array)
for (i=1;i<4,i++)
{
A[i][1]+= A[i-1][1]
}
What is the best (or straightforward) way to write this in scala functional style??
Thanks for any help!

Here you are:

val a = Array(Array(10, 1), Array(20, 2), Array(30, 1), Array(40, 3))
val b = a.scanLeft(Array(0, 0))((prev, cur) => Array(cur(0), prev(1) + cur(1))).tail
println(java.util.Arrays.deepToString(b.asInstanceOf[Array[Object]]))

Output:

[[10, 1], [20, 3], [30, 4], [40, 7]]
2 Likes

As a side-note to Tarsa’s answer, if you have an array of arrays of Int, and you want to mutate them in place, the best thing to do is use a while loop.

Everything else will kill your performance for little to no gain.

2 Likes

A little additional clarification: Array isn’t used anywhere near as often in Scala as it is in C++. Most idiomatic Scala code uses data types like List or Vector, which are intended to be used in an immutable functional style.

Array is primarily used in performance-critical code – and as @martijnhoekstra says, in performance-critical code, you would typically do this with a mutating while loop, throwing out the functional style, pretty much the same as C++.

2 Likes

Thanks all for the answers\clarifications!