w3resource

Scala Programming: Find the two elements from a given array of positive and negative numbers such that their sum is closest to zero

Scala Programming Array Exercise-29 with Solution

Write a Scala program to find the two elements from a given array of positive and negative numbers such that their sum is closest to zero.

Sample Solution:

Scala Code:

object Scala_Array {
  def main(args: Array[String]): Unit = {
    val arr = Array(1, 5, -4, 7, 8, -6)
    println("Original array:")
    for (x <- arr) {
      print(s"${x}, ")
    }
    val size = arr.length
    var min_sum, sum, min_l_num, min_r_num = 0
    val l, r = 0
    if (size >= 2) {
      var min_l_num = 0
      var min_r_num = 1
      var min_sum = arr(0) + arr(1)

      for (l <- 0 to size - 1) {

        for (r <- l + 1 to size - 1) {
          sum = arr(l) + arr(r);
          if (Math.abs(min_sum) > Math.abs(sum)) {
            min_sum = sum
            min_l_num = l
            min_r_num = r
          }
        }
      }

      println(s"\nTwo elements whose sum is minimum are ${arr(min_l_num)} and ${arr(min_r_num)}")  
    } 
    else {
      println("\nArray size less than two!")
    }
  }
} 

Sample Output:

Original array:
1, 5, -4, 7, 8, -6, 
Two elements whose sum is minimum are 5 and -4

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s.
Next: Write a Scala program to find all combination of four elements of a given array whose sum is equal to a given value.

What is the difficulty level of this exercise?