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.
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With