Question: I am searching a vector of vectors for a specific int.

```
  def searchVectors(i: Int, vectors: Vector[Vector[Int]]) = {
    val x = vectors.indexWhere(_.indexWhere(_ == i))
    val y = vectors(x).indexOf(y)
    (x, y)
  }

```

You can see I get the y twice. Firstly when computing x and then again when computing y.
Not good. How do I do it so I only compute y once?

Thanks

Answer: 
Here is a more functional approach to do it:

```
def searchVectors(i: Int, vectors: Vector[Vector[Int]]) = {
  val outer = vectors.toStream map (_.indexOf(i))
  outer.zipWithIndex.filter(_._1 != -1).headOption map (_.swap)
}

```

EDIT: I think I like this even better:

```
def searchVectors(i: Int, vectors: Vector[Vector[Int]]) = {
  vectors.toStream.map(_.indexOf(i)).zipWithIndex.collectFirst {
    case (y, x) if y != -1 => (x, y)
  }
}

```

Converting to a `Stream` is optional, but probably more efficient because it avoids searching the whole vector if the desired element has already been found.
Here's a easy-to-understand solution

```
def searchVectors(i: Int, vectors: Vector[Vector[Int]]): (Int, Int) = {
    val row = vectors.indexWhere(_.contains(i)) // Try to get index of vector containing element
    if (row > -1) (row, vectors(row).indexOf(i)) // (row, col)
    else (-1, -1)
}

```