Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

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
...