One approach you can take is to simply iterate over all the vectors:
def searchVectors(x: Int, vec: Vector[Vector[Int]]) = for { i <- 0 until vec.size j <- 0 until vec(i).size if vec(i)(j) == x } yield (i, j)
Vector also has a zipWithIndex method that adds an index to each element in the collection and creates a tuple from them. So you can use it to archive the same thing:
def searchVectors(x: Int, vec: Vector[Vector[Int]]) = for { (subVec, i) <- vec.zipWithIndex (elem, j) <- subVec.zipWithIndex if elem == x } yield (i, j)
The advantage of this approach is that instead of an outer (index-based) loop, you use an inner loop with map / flatMap . If you combine it with views, you can implement a lazy search:
def searchVectors(x: Int, vec: Vector[Vector[Int]]) = for { (subVec, i) <- vec.view.zipWithIndex (elem, j) <- subVec.view.zipWithIndex if elem == x } yield (i, j)
No, you will still receive a collection of results, but this is a lazy collection. Therefore, if you take it like this:
searchVectors(3, vector).headOption
It will perform a search (only at this point), and then when it is found, it will be returned as Option . No further searches will be performed.
source share