Scala : Remove consecutive duplicates from List

object scalaprolog extends App {

var list2=List(1,2,2,2,3,3,4,5,6,7,7,8,7,2,2)

def duplicate(l:List[Int]):List[Int]=
{
var testlist=scala.collection.mutable.ListBuffer.empty[Int]
testlist += l(0)
//testlist.toList
def loop(lis:List[Int],n:Int):List[Int]=
{

if(n<list2.length)
{ //println(n)
if (testlist.last != lis(n))
{println(testlist.last,lis(n))
testlist +=lis(n)

//loop(lis,n+1)
}
loop(lis,n+1)
}

testlist.toList

}
loop(list2,0)
testlist.toList
}
println(duplicate(list2) )
}

 

 

 

Output :

 

(1,2)
(2,3)
(3,4)
(4,5)
(5,6)
(6,7)
(7,8)
(8,7)
(7,2)
List(1, 2, 3, 4, 5, 6, 7, 8, 7, 2)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s