w3resource

Scala Programming: Replace every element with the next greatest element in a given array of integers

Scala Programming Array Exercise-34 with Solution

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.

Sample Solution:

Scala Code:

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, 

Scala Code Editor :

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

Previous: Write a Scala program to separate even and odd numbers of a given array of integers. Put all even numbers first, and then odd numbers.
Next: Write a Scala program to find all pairs of elements in an array whose sum is equal to a specified number.

What is the difficulty level of this exercise?