Reputation: 1647
I have 2 list
val listA = List("Mary", "Harry", "Marry", "Harry", "Marry")
val listB = List("Mary", "Harry", "Marry", "Harry", "Marry")
Now I want to know whether the index of all occurrences of Harry
in both the list are same or not. What is the best way to do it in scala?
Upvotes: 0
Views: 506
Reputation: 1019
I'd use iterators to compare only as much as needed, like so:
def indexesOf(ls: List[String], word: String) =
ls.iterator.zipWithIndex.collect { case (`word`, i) => i }
indexesOf(listA, "Harry") sameElements indexesOf(listB, "Harry")
Upvotes: 4
Reputation: 24802
You could .zip
the lists together and then use .exists
to check whether there is a tuple where one equals "Harry"
and the other does not:
scala> val listA = List("Mary", "Harry", "Marry", "Harry", "Marry")
listA: List[String] = List(Mary, Harry, Marry, Harry, Marry)
scala> val listB = List("Mary", "Harry", "Marry", "Harry", "Marry")
listB: List[String] = List(Mary, Harry, Marry, Harry, Marry)
scala> (listA zip listB).exists { case (a, b) => (a == "Harry" ^ b == "Harry") }
res5: Boolean = false
scala> val listA = List("Mary", "Harry", "Marry", "Harry", "Marry")
listA: List[String] = List(Mary, Harry, Marry, Harry, Marry)
scala> val listB = List("Mary", "Harry", "Marry", "Harry", "Harry") // changed the last one
listB: List[String] = List(Mary, Harry, Marry, Harry, Harry)
scala> (listA zip listB).exists { case (a, b) => (a == "Harry" ^ b == "Harry") }
res6: Boolean = true
Upvotes: 2