Tuesday, October 13, 2009

P09: Pack consecutive duplicates of list elements into sublists.

This might be a good candidate for recursive solution. But much faster iterative solution is shown below:


import scala.collection.mutable.ListBuffer
def unflatten[T](list:List[T]):List[List[T]]={
val uniq = list.removeDuplicates
val c = new ListBuffer[List[T]]()
var uniqv = uniq
while(!uniqv.isEmpty){
c.append(list.filter(_==uniqv.head))
uniqv=uniqv.tail
}
c.toList
}
val x = List(1,2,3,1,2,3,1,2,3,1,2,3)
println(unflatten(x))

Output:
List(List(1, 1, 1, 1), List(2, 2, 2, 2), List(3, 3, 3, 3))

No comments:

Post a Comment