Francesco Francesco - 3 months ago 12
Scala Question

Scala: count entries from a list in a matrix

I first need to say that I am quite new to Scala's collections' map reduce kind of functions.

What I am trying to do is counting for each row of a matrix, how many times (all) the elements of a list (in this case numbers from 0 to n) appear. The ideal output would be a matrix with the same number of rows of the input matrix and as many columns as the length of the list.
For example:

val list = List(0,1,2)

val matrix = Array(
Array(0,1,2,2),
Array(0,0,1,0),
Array(2,0,2,0))


in this case I would like to obtain such a matrix

1 1 2
3 1 0
2 0 2


What I came up with so far is the following:

val counts = matrix.map(r => r.map(x => (x,r.count(_ == x))).groupBy(_._1))


where the first part (up to groupBy) gives, for each row, couples of the kind (element, count). Then I tried to group this, but it doesn't quite work as I expected.

This is of course very far away from what I'd like to achieve,as it just counts the elements in the matrix (so would never give a 0).

Also, being in topic, is Array[Array[Type]] the best practice for dealing with matrices in Scala (given that no linear algebra should be applied, but rather counts and reading)?

Thank you.

Answer

For each row r in matrix, map each item i in list into the number of its occurrences in r:

matrix.map(r => list.map(i => r.count(_ == i)))