w3resource

Scala Programming: Remove duplicate elements from an array of integers

Scala Programming Array Exercise-18 with Solution

Write a Scala program to remove duplicate elements from an array of integers.

Sample Solution:

Scala Code:

object Scala_Array {   
   def main(args: Array[String]): Unit = {     
     var my_array = Array(0, 0, 3, -2, -2, 4, 3, 2, 4, 6, 7)    
     //Call the following java class for array operation     
     import java.util.Arrays; 
     println("Original Array1 : "+Arrays.toString(my_array));     
     var no_unique_elements = my_array.length;         
     //Comparing each element with all other elements         
       var i=0;
       var j=0;
      // var j=0;
       for (l <- 0 to no_unique_elements-1) 
        {          
          j=i+1
        //  println(i + "  "+j)
          for (x <- i+1 to no_unique_elements-1)
            {
                //If any two elements are found equal                 
                if (my_array(i) == my_array(j))
                {
                    //Replace duplicate element with last unique element                     
                    my_array(j) = my_array(no_unique_elements-1);
                     no_unique_elements = no_unique_elements-1;                     
                   j=j-1      
                }    
              j=j+1
             }
           i=i+1
        }  
     //Copying only unique elements of unique_array into array1
     //Use the Java class for array operation         
       var unique_array = Arrays.copyOf(my_array, no_unique_elements);                
       println("New array without duplicates: "+Arrays.toString(unique_array));
   }
 }

Sample Output:

Original Array1 : [0, 0, 3, -2, -2, 4, 3, 2, 4, 6, 7]
New array without duplicates: [0, 7, 3, -2, 4, 2, 6]

Scala Code Editor :

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

Previous: Write a Scala program to remove duplicate elements from an array of strings.
Next: Write a Scala program to find the second largest element from a given array of integers.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/scala-exercises/array/scala-array-exercise-18.php