Home > Mobile >  Filter Scala Matrix with condition
Filter Scala Matrix with condition

Time:03-09

I have the given matrix in Scala:

val matrix = Array([30, 0, 13, 21, 25, 15], 
                   [55, 47, 26, 54, 44, 3],
                   [21, 19, 23, 47, 29, 13],
                   [52, 50, 44, 14, 21, 24],
                   [10, 37, 0, 22, 17, 58],
                   [36, 55, 48, 27, 13, 35])

I need to filter the matrix (values from 2nd column > 40 and values fom 4rd column <45)

Can i do this somehow with the matrix.filter method?

CodePudding user response:

You can try this way:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val matrix = Array(Array(30, 0, 13, 21, 25, 15),
                   Array(55, 47, 26, 54, 44, 3),
                   Array(21, 19, 23, 47, 29, 13),
                   Array(52, 50, 44, 14, 21, 24),
                   Array(10, 37, 0, 22, 17, 58),
                   Array(36, 55, 48, 27, 13, 35))

// Exiting paste mode, now interpreting.

matrix: Array[Array[Int]] = Array(Array(30, 0, 13, 21, 25, 15), Array(55, 47, 26, 54, 44, 3), Array(21, 19, 23, 47, 29, 13), Array(52, 50, 44, 14, 21, 24), Array(10, 37, 0, 22, 17, 58), Array(36, 55, 48, 27, 13, 35))

scala> matrix.filter(x => x(1) > 40 && x(3) < 45)
res0: Array[Array[Int]] = Array(Array(52, 50, 44, 14, 21, 24), Array(36, 55, 48, 27, 13, 35))

CodePudding user response:

Thanks, that helped me a lot! Was not that hard after all!

  • Related