Search code examples
scalaexceptionsyntax

Find duplicates in a given Array - Index 5 out of bounds for length 4 when I'm doing foldLeft in Scala


I only try to find duplicates in a given array. My code is:

 def findDuplicates(nums: Array[Int]): List[Int] = {
nums.map(transformValues(nums)).toList

}

def transformValues(nums: Array[Int]): Array[Int] = {
    nums.foldLeft(Array[Int]())((accumValue, nextEl) => {
      if (nums.tail.contains(nextEl)) accumValue :+ nextEl
      else accumValue
    })
  }

  val arr = Array(5, 1, 1, 1, 2)
  println(findDuplicates(arr))

The result should be Array(1, 1, 1), but instead I receive an exception, I also tried to debug and found out that in the row nums.map(transformValues(nums)).toList it returns the initial array. Could someone help me to understand what is wrong?


Solution

  • Your first map operation is likely not what you expect.

    It's the same as:

    nums.map(x => transformValues(nums)(x))
    

    Meaning you're calling transformValues and retrieving the x-th item of the response but there's no guarantee it exists.