Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove consecutive identical elements in scala

Tags:

scala

I have a list which may contain certain consecutive identical elements.I want to replace many consecutive identical elements with one. How to do it in scala

Lets say my list is

List(5, 7, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)

I want output list as

List(5, 7, 2, 3, 5, 3, 2)
like image 748
kundan kanan Avatar asked Mar 30 '15 05:03

kundan kanan


1 Answers

It can be done pretty cleanly using sliding:

myList.head :: myList.sliding(2).collect { case Seq(a,b) if a != b => b }.toList

It looks at all the pairs, and for every non-matching pair (a,b), it gives you back b. But then it has to stick the original a on the front of the list.

like image 53
dhg Avatar answered Oct 17 '22 10:10

dhg