Reputation: 413
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.
EDIT: By rows was solved, but what if the same needs to be done on the columns? I guess transpose should be avoided if the matrix is very large.
Upvotes: 1
Views: 635
Reputation: 37832
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)))
Upvotes: 1
Reputation: 75
Using foldLeft:
matrix.map { row => {row.foldLeft(Array(0,0,0))((r,e)=> {if(list.contains(e)) {r(e) += 1}; r})}}
Upvotes: 0
Reputation: 413
In the meanwhile I came up with such solution, but I'm pretty sure there is a more compact and idiomatic way to do so.
def count_list_row(row: Array[Int], tot_elements: Int): Array[Int] ={
val counts = new Array[Int](tot_elements)
for(element <- 0 until tot_elements){
counts(element) = row.count(_ == element)
}
return counts
}
val counts = matrix.map(r => count_list_row(r,2))
Upvotes: 0