w3resource

Scala Programming: Find all combination of four elements of a given array whose sum is equal to a given value


Write a Scala program to find all combination of four elements of a given array whose sum is equal to a given value.

Sample Solution:

Scala Code:

object Scala_Array {
  def main(args: Array[String]): Unit = {
    val nums = Array(10, 20, 30, 40, 1, 2);
    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }
    val n = nums.length;
    // given value
    val s = 53;
    println("\nGiven value: " + s);
    println("Combination of four elements:");
    // Find other three elements after fixing first element
    for (i <- 0 to n - 4) {
      // Find other two elements after fixing second element
      for (j <- i + 1 to n - 3) {
        // Find the fourth element after fixing third element
        for (k <- j + 1 to n - 2) {
          // find the fourth
          for (l <- k + 1 to n - 1) {
            if (nums(i) + nums(j) + nums(k) + nums(l) == s)
              println(
                "\n" + nums(i) + " " + nums(j) + " " + nums(k)
                  + " " + nums(l)
              );
          }
        }
      }
    }

  }

}

Sample Output:

Original array:
10, 20, 30, 40, 1, 2, 
Given value: 53
Combination of four elements:
10 40 1 2
20 30 1 2

Go to:


PREV : 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.
NEXT : Write a Scala program to count the number of possible triangles from a given unsorted array of positive integers.

Scala Code Editor :

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

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.