w3resource

Scala Programming: Pairs of elements in an array whose sum is equal to a specified number

Scala Programming Array Exercise-35 with Solution

Write a Scala program to find all pairs of elements in an array whose sum is equal to a specified number.

Sample Solution:

Scala Code:

object Scala_Array {

  def test(inputArray: Array[Int], inputNumber: Int): Unit = {
    println("Pairs of elements and their sum : ");
    for (i <- 0 to inputArray.length - 1) {
      for (j <- i + 1 to inputArray.length - 1) {
        if (inputArray(i) + inputArray(j) == inputNumber) {
          println(s"${inputArray(i)} + ${inputArray(j)} = ${inputNumber}");
        }
      }
    }

  }

  def main(args: Array[String]): Unit = {
    val nums1 = Array(2, 7, 4, -5, 11, 5, 20);
    println("Original array:")
    for (x <- nums1) {
      print(s"${x}, ")
    }
    var n1 = 15;
    println(s"\nSpecified Number: ${n1}")
    test(nums1, n1);

    val nums2 = Array(14, -15, 9, 16, 25, 45, 12, 8);
    println("Original array:")
    for (x <- nums2) {
      print(s"${x}, ")
    }
    n1 = 30;
    println(s"\nSpecified Number: ${n1}")
    test(nums2, n1);
  }
}

Sample Output:

Original array:
2, 7, 4, -5, 11, 5, 20, 
Specified Number: 15
Pairs of elements and their sum : 
4 + 11 = 15
-5 + 20 = 15
Original array:
14, -15, 9, 16, 25, 45, 12, 8, 
Specified Number: 30
Pairs of elements and their sum : 
14 + 16 = 30
-15 + 45 = 30

Scala Code Editor :

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

Previous: Write a Scala program to replace every element with the next greatest element (from right side) in a given array of integers. There is no element next to the last element, therefore replace it with -1.
Next: Write a Scala program to find maximum product of two integers in a given array of integers.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.