New to Scala. I have data of the form List[Array[Int]],each Array[Int] has n integers, call this a. There are also two Array[int], call them c and d, also of length n. I want to compare each element of each row of a to the corresponding element of c and d (i.e, of same index) and return those rows that match c or d.
Nothing at stake here, just self teaching Scala.
CodePudding user response:
Examples are better than explanations (don't describe, demonstrate) so it's a little hard to know if this is what you're getting at.
val data = List(Array( 2, 4, 6) // a
,Array(11,44, 6) // c
,Array(12, 4,66)) // d
data.transpose
.flatMap(grp => grp.tail.find(_ == grp.head))
//res0: List[Int] = List(4, 6)
This is a bit dangerous in that all the arrays must be non-empty and the same length.
CodePudding user response:
Assuming this starting point:
val c = Array(1,2,3)
val d = Array(0,1,2)
val target: List[Array[Int]] = List(c,d)
val as: List[Array[Int]] =
List(
Array(0,1,2),
Array(1,2,3),
Array(2,3,4),
Array(4,5,6),
)
Here is how to get only the arrays from as
that match exactly c
or d
:
as
.filter(a => a.sameElements(c) || a.sameElements(d))
//and a bit more generic if you have a big target pool
as
.filter(a => target.exists(_.sameElements(a)))
This solution is resilient to possible empty or different sizes arrays in as
.