Scala Programming: Remove the duplicate elements of a given array and return the new length of the array
Scala Programming Array Exercise-26 with Solution
Write a Scala program to remove the duplicate elements of a given sorted array and return the new length of the array.
Sample array: [20, 20, 30, 40, 50, 50, 50, 50, 60, 60]
After removing the duplicate elements the program should return 5 as the new length of the array
Sample Solution:
Scala Code:
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
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Next: Write a Scala program to find smallest and second smallest elements of a given array.What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/array/scala-array-exercise-26.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics