sowmiyaksr
sowmiyaksr

Reputation: 169

Compare two list and get the index of same elements

val a = List(1,1,1,0,0,2)
val b = List(1,0,3,2)

I want to get the List of indices of elements of "List b" which are existing in "List a". Here output to be List(0,1,3)

I tried this

for(x <- a.filter(b.contains(_))) yield a.indexOf(x))

Sorry. I missed this. The list size may vary. Edited the Lists

Is there a better way to do this?

Upvotes: 1

Views: 2203

Answers (5)

Akavall
Akavall

Reputation: 86188

Here is another option:

scala> val a = List(1,1,1,0,0,2)
a: List[Int] = List(1, 1, 1, 0, 0, 2)

scala> val b = List(1,0,3,2)
b: List[Int] = List(1, 0, 3, 2)

scala> b.zipWithIndex.filter(x => a.contains(x._1)).map(x => x._2)
res7: List[Int] = List(0, 1, 3)

I also want to point out that your original idea of: Finding elements in b that are in a and then getting indices of those elements would not work, unless all elements in b contained in a are unique, indexOf returns index of the first element. Just heads up.

Upvotes: 0

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20088

scala> for(x <- b.indices.filter(a contains b(_))) yield x;
res27: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 3)

Upvotes: 1

alaptiko
alaptiko

Reputation: 509

You can use indexed for for this:

for{ i <- 0 to b.length-1
     if (a contains b(i))
   } yield i

Upvotes: 3

jwvh
jwvh

Reputation: 51271

If you want a result of indices, it's often useful to start with indices.

b.indices.filter(a contains b(_))

REPL tested.

scala> val a = List(1,1,1,0,0,2)
a: List[Int] = List(1, 1, 1, 0, 0, 2)

scala> val b = List(1,0,3,2)
b: List[Int] = List(1, 0, 3, 2)

scala> b.indices.filter(a contains b(_))
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 3)

Upvotes: 3

insan-e
insan-e

Reputation: 3921

val result = (a zip b).zipWithIndex.flatMap {
  case ((aItem, bItem), index) => if(aItem == bItem) Option(index) else None
}

a zip b will return all elements from a that have a matching pair in b. For example, if a is longer, like in your example, the result would be List((1,1),(1,0),(1,3),(0,2)) (the list will be b.length long).
Then you need the index also, that's zipWithIndex.
Since you only want the indexes, you return an Option[Int] and flatten it.

Upvotes: 3

Related Questions