Reputation: 19
I am trying out to compare list of list values with another list and return if matched.I am looking it in scala however i am new into scala and it difficult to do if any suggestions please pass on
val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))
val l2 = List(1,2,3,12)
so here trying to compare l1([1,2,3])
with l2 [1,2,3,12]
and l1 [11,12,13]
with l2 [1,2,3,12]
and return if not matched any elements from l1 to l2.
here we are looking for of l1 any value matched with l2 then 0 else 1
Tricky but is it doable in scala?Any suggestions
Upvotes: 0
Views: 192
Reputation: 3638
From the initial set of requirements that you have provided, the following solution will solve your problem
val l1 = List(List(1,12.34,76.456,12,List(1,2,3)),List(2,12.43,76.256,12,List(11,12,13)))
val l2 = List(11,12,13)
l1.flatten.filter(_.isInstanceOf[List[Int]]).map(x =>
if(x == l2) 0 else 1)
This gives you a result whether the list l2 matches inner list of l1 or not.
res1: List[Int] = List(1, 0)
Upvotes: 0
Reputation: 2397
You need to flatten l1
. to make it generic (because as I understand, l1
can be list of list of list..) you can create a generic method which flatten it:
def flatten[T](l: List[T]): List[T] = l match {
case Nil => Nil
case (x: List[T]) :: tail => flatten(x) ::: flatten(tail)
case x :: tail => x :: flatten(tail)
}
Then, you can get the result it by:
(l2.map(flatten(l1).contains)).map(_.compare(false)) // List(1,1,1,1)
Here is the code to run and debug - https://scalafiddle.io/sf/3SStZZX/1
Upvotes: 0