Write a Scala program to count the number of possible triangles from a given unsorted array of positive integers
- برمجة سكالا
- 2021-09-24
- mhanasmh00489829403
الأجوبة
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
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال
معلومات ذات صلة