Thursday, October 8, 2009

P08: Eliminate consecutive duplicates of list elements.

The simple solution:
scala> val x = List(1,2,2,3,4,4,5,5)
x: List[Int] = List(1, 2, 2, 3, 4, 4, 5, 5)

scala> x.removeDuplicates
res0: List[Int] = List(1, 2, 3, 4, 5)

For the curious under the hood:

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> def myRemoveDuplicates[T](in:List[T]):List[T] = {
| val b = new ListBuffer[T]
| var temp = in
| while(!temp.isEmpty){
| if(!temp.tail.contains(temp.head)) b+=temp.head
| temp = temp.tail
| }
| b.toList
| }
myRemoveDuplicates: [T](in: List[T])List[T]

scala> myRemoveDuplicates(x)
res2: List[Int] = List(1, 2, 3, 4, 5)

No comments:

Post a Comment