1

I have a two dimension collection(say Vector[Vector[Int]]) and I want to find the index of a element in it. My solution is like:

def find(vec: Vector[Vector[Int]], target: Int) = {
  def indexOfTarget(v: Vector[Int]) = v.indexOf(target)

  val r = vec.indexWhere((v) => indexOfTarget(v) != -1)
  val c = indexOfTarget(vec(r))

  (r, c)
}

But it's just... ugly. And it invokes indexOfTarget one more time than necessary.

Is there a better way?

4

3 回答 3

3

怎么样:

vec.view.zipWithIndex.map {
  case (iv,i) => (i, iv.indexOf(target))
}.find(_._2 != -1)

请注意,由于view,zipWithIndexmap被懒惰地评估,因此这只进行了绝对需要的计算。

于 2013-05-08T00:52:38.923 回答
0

An implementation that returns Some((x, y)) if the element is present, and None otherwise:

def find(vec: Vector[Vector[Int]], target: Int) = (for {
  (xs, posX) <- vec.view.zipWithIndex
  (`target`, posY)  <- xs.view.zipWithIndex
} yield (posX, posY) ).headOption


scala> find(Vector(Vector(1, 2, 4), Vector(2, 2, 3)), 3)
res0: Option[(Int, Int)] = Some((1,2))
于 2013-05-08T12:58:25.590 回答
0

你可以试试这个:

def find(vec: Vector[Vector[Int]], target: Int) = {
  val zipped = vec.zipWithIndex
  val result = for{
    tup <- zipped
    index <- List(tup._1.indexOf(target))
    if (index != -1)
  } yield (tup._2, index)
  result.headOption
}

如果不匹配Option[(Int,Int)],结果类型将是一个。None

于 2013-05-08T00:58:33.330 回答