Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now