Home > Blockchain >  How to have the total sum of all the numbers contained in a matrix?
How to have the total sum of all the numbers contained in a matrix?

Time:12-14

I'm a beginner in Scala and I'm trying to build a function that calculates the total sum of all the numbers contained in a matrix. I tried to do this code :

val pixels = Vector(
Vector(0, 1, 2),
Vector(1, 2, 3)
)

def sum(matrix: Vector[Vector[Int]]): Int = {
matrix.reduce((a, b) => a   b)
}

println(sum(pixels))

But I get the following error: "value is not a member of Vector[Int]"

I would like to have the sum total of all the numbers contained in the matrix as an integer.

Can you help me to solve this problem ?

Thank you in advance !

CodePudding user response:

You defined matrix as a Vector of Vectors, so arguments to reduce are two Vectors, not ints. If you want to sum the all, you need to flatten first to pull the actual ints from the inner vectors. Also your function the way you wrote it does not return anything. You don't want that variable assignment:

def sum(matrix: Vector[Vector[Int]]) = matrix.flatten.reduce(_ _)

  • Related