-2

I am new to scala How can I remove Duplicates from an array. without using Distict keyword.

I have Array Like this

Input 

Array(1,2,3,1,3)
=====================

I need output like This

OutPut
====================
Array(1,2,3)

My code is

Val ar=Array(1,2,3,4,5)
for(i<-0  to ar.length-1){
if(ar(i)!=for())..?

I want to write a program without using Set And List

val dup =ar.foldLeft(Array[Int]()){(a,b)=>if(a contains(b)) a else a :+ b}

I got this solution but how it works

can any one please explain how background it works I tried

1,2,3,1,2
1==2 false .. else 1 : 
2

3 Answers 3

2

It seems a bit arbitrary to not want to use .distinct. But you could always turn it into a set and back.

Array(1,2,3,1,3).toSet.toArray 
res2: Array[Int] = Array(1, 2, 3)
Sign up to request clarification or add additional context in comments.

2 Comments

Nope I know this Way But I need core
Without using Set and GroupBy without using Methods and Set and List
1

Here's a very inefficient algorithm. It doesn't use distinct, Set, or groupBy.

Array(1,2,3,1,3).foldLeft(Array[Int]()){ (acc,elem) =>
  if (acc.contains(elem)) acc else acc :+ elem
}

3 Comments

Thanks Its Working
what does :+ do here
acc :+ elem creates a copy of acc with the element elem appended.
1

If you are OK with having your unique Array in sorted order, you can sort your original array, and only keep elements that are not equal to their neighbors:

object MyOjbect {

def makeUnique(a: Array[Int]): Array[Int] = { 
    if (a.isEmpty) return Array()

    a.head +: a.sorted.sliding(2).foldLeft(Array[Int]()) { (acc, ele) =>
                   if (ele(0) != ele(1)) acc :+ ele(1) else acc 
                   }
}   

def main(args: Array[String]) {

    println(makeUnique(Array(1,2,3,1,3)).toList) 
    println(makeUnique(Array(1,1,1,1,1)).toList)
    println(makeUnique(Array()).toList)
    }
}

Result:

List(1, 2, 3)
List(1)
List()

5 Comments

What :+ will do
what does :+ do exactly
@Ravi, :+ creates a new Array, for example: val b = Array(1,2,3) :+ 4 will create a new Array b, whose contents are: Array(1, 2, 3, 4).
But I have used for List as well ya its working val l=List(1,2,3,1,2).foldLeft(List[Int]()){(a,b)=>if(a contains(b)) a else a :+ b}.foreach(println(_))
@Ravi, Yes, :+ is a method on scala collections (Array, List, Seq, Vector maybe more), so it works on all of them; it creates a new collection including a new variable, like in example I gave above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.