Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala way to remove duplicate in an Array

Tags:

scala

I want to learn how to write for loop functions without declear "var" at the front of the code. For example, I want to remove duplicates in an interger Array. In C++/Java, I can do like that:

int removeDuplicate(vector<int> nums)
{
     vector<int> output
     Map<int,int> counter;
     for(i = 0; i < nums.size(); i++)
     {
         if(!counter.has_key(nums[i]))
         {
             counter[nums[i]]=1;  //add new key-value pair
             output.push_back(nums[i]);
         }
     }

     return output;
}

But in scala, how to use immutable variables to complete above task.

Do NOT use scala's internal functions, such as distinct. This question is about Scala implementation.

like image 860
lserlohn Avatar asked Sep 09 '17 01:09

lserlohn


People also ask

How can I remove the duplicate items in an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


2 Answers

In Scala to avoid using vars in this case you can use recursion or foldLeft or foldRight:

def distinct[A](list:List[A]):List[A] = 
  list.foldLeft(List[A]()) {
    case (acc, item) if acc.contains(item) => acc
    case (acc, item) => item::acc
  }   
like image 54
Nyavro Avatar answered Nov 15 '22 06:11

Nyavro


Scala provides lots of library functions. Like, there is distinct function. You can directly call it.

scala> val array = Array(1,2,3,2,1,4)
array: Array[Int] = Array(1, 2, 3, 2, 1, 4)
scala> array.distinct
res0: Array[Int] = Array(1, 2, 3, 4)

And if there is no library function, we prefer to write code using recursion mostly tail recursion so that we can maintain immutability. Or you may convert array into Set which will remove duplicates and then convert set into array again to get desired result.

scala> array.toSet.toArray
res3: Array[Int] = Array(1, 2, 3, 4)

In scala, list is preferred over array as array is mutable collection in scala and list is immutable. So prefer to use it.

like image 42
Mahesh Chand Avatar answered Nov 15 '22 05:11

Mahesh Chand