Scala way to remove duplicate in array

I want to learn how to write for loop functions without the delicate "var" at the beginning of the code. For example, I want to remove duplicates in a gateway. In C ++ / Java, I can do this:

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 accomplish the above task.

DO NOT use scala's internal functions, for example distinct. This question is about scala implementation.

+4
source share
3 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
  }   
+8
source

Scala provides many library features. For example, there is a clear function. You can call him directly.

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)

, , , , , . Set, , , .

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

scala , , scala, . .

+1

There are several ways to do this in Scala (without clear ones). All of these alternatives use immutable variables:

Using groupBy :

val x: Seq[Int] = Seq(1,2,3,3,4,5,6,6)
val unique: Seq[Int] = x.groupBy(identity).keys.toSeq

Using toSet :

val x: Seq[Int] = Seq(1,2,3,3,4,5,6,6)
val unique: Seq[Int] = x.toSet.toSeq
0
source

Source: https://habr.com/ru/post/1685339/


All Articles