Write a Scala program to replace every element with the next greatest element (from right side) in a given array of integers. There is no element next to the last element, therefore replace it with -1.
object Scala_Array { def test(arr_nums: Array[Int]): Array[Int] = { val size = arr_nums.length; var max_from_right_num = arr_nums(size - 1); arr_nums(size - 1) = -1; var temp = 0 for (i <- size - 2 to 0 by -1) { temp = arr_nums(i); arr_nums(i) = max_from_right_num; if (max_from_right_num < temp) max_from_right_num = temp; } arr_nums; } def main(args: Array[String]): Unit = { val nums = Array(45, 20, 100, 23, -5, 2, -6); println("Original array:"); for (x <- nums) { print(s"${x}, ") } val result = test(nums); println("\nThe modified array:"); for (x <- result) { print(s"${x}, ") } } }
Sample Output:
Original array: 45, 20, 100, 23, -5, 2, -6, The modified array: 100, 100, 23, 2, 2, -6, -1,
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer