Write a Scala program to find all combination of four elements of a given array whose sum is equal to a given value
- برمجة سكالا
- 2021-09-24
- mhanasmh00489829403
الأجوبة
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
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال
معلومات ذات صلة