Search code examples
scalaarraybuffer

How to check the existence of a value in an ArrayBuffer?


I am new in Scala and I am writing a program in which I have an ArrayBuffer of points of a binary image and I want to check in a loop if a specific point is existing in that ArrayBuffer do not add. This is the part of code I am working on :

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)) {//this is where I want to check if the current point (value1,value2) is already exists in vectVisitedPoint
                                    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
            }
    }
}

I think I need to write it in another way but don't know how?!

Thanks.


Solution

  • You can use:

    vectVisitedPoint.exists(_ == (value1, value2))
    

    Would you like me to refactor your code for you into much much less code, more functional, more readible and probably more efficient way? If so create another question and I will.