在Scala中检索多维数组中有界元素的最大索引

Pau*_*ius 4 arrays indexing scala indices

我有一个多维数组:

val M = Array.ofDim[Int](V, N)
Run Code Online (Sandbox Code Playgroud)

目标是找到最大的V维度索引,其中存在有界元素0 <w0 <= W并返回索引和元素值.

目前我有这个代码片段可以工作,但想知道是否有更好,更有效的方法来做到这一点.

M.zipWithIndex.reverse.collectFirst({
  case (arr, ind) if arr.exists(a => a <= W && a > 0) => {
    arr.zipWithIndex.find(a => a._1 <= W && a._1 > 0) match {
      case Some((weight, ind2)) => (ind, ind2, weight)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

Lui*_*hys 5

嗯,与其他人非常相似,但是当它找到目标时就会停止

def find(M: Array[Array[Int]], W: Int): Option[(Int, Int, Int)] = {
  for {
    x <- M.indices.reverse
    y <- M(x).indices
    a = M(x)(y)
    if 0 < a && a <= W
  } return Some(x, y, a)
  None
}
Run Code Online (Sandbox Code Playgroud)