How to implement the two sum algorithm to find two values in array that add up to target with Scala

1 Answer

0 votes
import scala.util.boundary

object TwoSumExample {
  def twoSum(arr: Array[Int], target: Int): Option[(Int, Int)] = boundary {
    for (i <- arr.indices; j <- i + 1 until arr.length) {
      if (arr(i) + arr(j) == target) {
        boundary.break(Some((i, j))) // Correct non-local return
      }
    }
    None // No match found
  }

  def main(args: Array[String]): Unit = {
    val array1 = Array(1, 5, 7, 4, 3, 2)
    val array2 = Array(3, 1, 4, 2, 5)

    twoSum(array1, 9) match {
      case Some((i, j)) => println(s"Indices: ($i, $j), Numbers: (${array1(i)}, ${array1(j)})")
      case None         => println("No matching pair found.")
    }

    twoSum(array2, 8) match {
      case Some((i, j)) => println(s"Indices: ($i, $j), Numbers: (${array2(i)}, ${array2(j)})")
      case None         => println("No matching pair found.")
    }
  }
}


 
/*
run:

Indices: (1, 3), Numbers: (5, 4)
Indices: (0, 4), Numbers: (3, 5)

*/

 



answered May 22, 2025 by avibootz
...