How to change the following code into more functio

2019-08-15 23:28发布

问题:

I'm working on a code to find the longest branch and here is a function to find the next unvisited point in my binary image: Note: I am saving the arraybuffer of found pixels in vectVisitedPoint.

var vectVisitedPoint= new scala.collection.mutable.ArrayBuffer[Point]()
    var pTemp=new Point (0,0)
    var res = new Array[Byte](1)
    img.get(pTemp.x.toInt,pTemp.y.toInt,res) //img is a binary image
    var value1: Int=0
    var value2: Int=0
    scala.util.control.Breaks.breakable {
            while((value1 < img.rows ) ){
                    while ( (value2 < img.cols )){
                             if (res(0) == -1 && vectVisitedPoint.exists(_ == (value1, value2))) {
                                    pTemp.x=(pTemp.x.toInt)+value1
                                    pTemp.y=(pTemp.y.toInt)+value2
                                    vectVisitedPoint.append(new Point(pTemp.x,pTemp.y)
                                    scala.util.control.Breaks.break()
                              }
                    value2=value2+1
                    img.get(value1,value2,res)
                    }
            value2=0
            value1=value1+1
            }
    }
}

回答1:

4e6 is probably correct in his comment (sorry, my fault), there is maybe too much code here to be an SO question, usually questions of the form "what is the Scala equivalent of ..." are accepted but perhaps some feel this question isn't really of that form. Nevertheless I'll answer it here and the mods can move it if they like

def longestBranch(binImage: TypeOfBinImage): Vector[Point] = {
  var res = new Array[Byte](1)

  def getRes(x: Int, y: Int) = {
    binImage.get(x, y, res)
    res
  }

  (0 until img.rows).foldLeft(Vector.empty[Point])((visited, x) => 
    (0 until img.cols).find(y => 
      getRes(x, y)(0) == -1 && visited.exists(_ == (x, y)))
    .map(y => visited :+ new Point(visited.last + x, visited.last + y))
    .getOrElse(visited)
  )
}

Note: I don't think this is more/less efficient, but it certainly is more Scalaery



标签: scala