Q:

Write a Scala program to remove the duplicate elements of a given sorted array and return the new length of the array

0

Write a Scala program to remove the duplicate elements of a given sorted array and return the new length of the array.

All Answers

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

object Scala_Array {
  def test(nums: Array[Int]) : Int = {
    var index = 1;
        for (i <- 0 to nums.length-1) {
            if (nums(i) != nums(index))
           {
               index += 1
               nums(index) = nums(i)
              }
        }
	  index;
  }  
  
  def main(args: Array[String]): Unit = {
    val nums = Array(20, 20, 30, 40, 50, 50, 50, 50, 60, 60);  
	  println(s"Original array length: ${nums.length}");
		println("Array elements are: ");
      for (i <- 0 to nums.length - 1) 
        {
             print(s"${nums(i)} ");
        }
		println(s"\nThe new length of the array after removing the duplicate elements is: ${test(nums)}");
      }
  }

Sample Output:

Original array length: 10
Array elements are: 
20 20 30 40 50 50 50 50 60 60 
The new length of the array after removing the duplicate elements is: 5

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