It is not only ineffective, but also dangerous. What if we change a little?
val row = table indexWhere (_.indexOf(101) != -1) val col = table(row) indexOf 42
It really looks like an expression for an expression:
val z = for { i <- 0 until table.length j <- 0 until table(i).length if (table(i)(j) == 42) } yield (i, j) z.headOption.getOrElse(-1, -1)
It may be too important, but it all translates to flatMap and filter under the hood. You could write it with this, but it is much more readable.
Edit: if you need fast execution, the recursive solution will match the score:
def findElement(table: Vector[Vector[Int]], elem: Int): (Int, Int) = { @tailrec def feRec(row: Int, col: Int): (Int, Int) = { if (row == table.length) (-1, -1) else if (col == table(row).length) feRec(row + 1, 0) else if (table(row)(col) == elem) (row, col) else feRec(row, col + 1) } feRec(0, 0) }
source share