w3resource

Scala Programming: Count the number of possible triangles from a given unsorted array of positive integers

Scala Programming Array Exercise-31 with Solution

Write a Scala program to count the number of possible triangles from a given unsorted array of positive integers.

Note: The triangle inequality states that the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side.

Sample Solution:

Scala Code:

object Scala_Array {
  def main(args: Array[String]): Unit = {
    val nums = Array(6, 7, 9, 16, 25, 12, 30, 40)
    val n = nums.length;
    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }
    scala.util.Sorting.quickSort(nums)
    // Initialize count of triangles
    var ctr = 0;
    var x = 0;
    for (i <- 0 to n - 2) {
      x = i + 2;
      for (j <- i + 1 to n - 1) {
        while (x < n && nums(i) + nums(j) > nums(x)) x = x + 1;
        ctr += x - j - 1;

      }
    }
    println(s"\nTotal number of triangles: ${ctr}");
  }
}

Sample Output:

Original array:
6, 7, 9, 16, 25, 12, 30, 40, 
Total number of triangles: 17

Scala Code Editor :

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

Previous: Write a Scala program to find all combination of four elements of a given array whose sum is equal to a given value.
Next: Write a Java program to arrange the elements of a given array of integers where all positive integers appear before all the negative integers.

What is the difficulty level of this exercise?